LCOV - code coverage report
Current view: top level - lib/TableGen - TGParser.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 809 1083 74.7 %
Date: 2018-02-23 15:42:53 Functions: 44 44 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===- TGParser.cpp - Parser for TableGen Files ---------------------------===//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : //
      10             : // Implement the Parser for TableGen.
      11             : //
      12             : //===----------------------------------------------------------------------===//
      13             : 
      14             : #include "TGParser.h"
      15             : #include "llvm/ADT/None.h"
      16             : #include "llvm/ADT/STLExtras.h"
      17             : #include "llvm/ADT/SmallVector.h"
      18             : #include "llvm/ADT/StringExtras.h"
      19             : #include "llvm/Support/Casting.h"
      20             : #include "llvm/Support/Compiler.h"
      21             : #include "llvm/Support/ErrorHandling.h"
      22             : #include "llvm/Support/raw_ostream.h"
      23             : #include "llvm/TableGen/Record.h"
      24             : #include <algorithm>
      25             : #include <cassert>
      26             : #include <cstdint>
      27             : 
      28             : using namespace llvm;
      29             : 
      30             : //===----------------------------------------------------------------------===//
      31             : // Support Code for the Semantic Actions.
      32             : //===----------------------------------------------------------------------===//
      33             : 
      34             : namespace llvm {
      35             : 
      36     1627071 : struct SubClassReference {
      37             :   SMRange RefRange;
      38             :   Record *Rec;
      39             :   SmallVector<Init*, 4> TemplateArgs;
      40             : 
      41     4018692 :   SubClassReference() : Rec(nullptr) {}
      42             : 
      43             :   bool isInvalid() const { return Rec == nullptr; }
      44             : };
      45             : 
      46          55 : struct SubMultiClassReference {
      47             :   SMRange RefRange;
      48             :   MultiClass *MC;
      49             :   SmallVector<Init*, 4> TemplateArgs;
      50             : 
      51        1822 :   SubMultiClassReference() : MC(nullptr) {}
      52             : 
      53             :   bool isInvalid() const { return MC == nullptr; }
      54             :   void dump() const;
      55             : };
      56             : 
      57             : #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
      58             : LLVM_DUMP_METHOD void SubMultiClassReference::dump() const {
      59             :   errs() << "Multiclass:\n";
      60             : 
      61             :   MC->dump();
      62             : 
      63             :   errs() << "Template args:\n";
      64             :   for (Init *TA : TemplateArgs)
      65             :     TA->dump();
      66             : }
      67             : #endif
      68             : 
      69             : } // end namespace llvm
      70             : 
      71   103627029 : bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
      72   103627029 :   if (!CurRec)
      73       89270 :     CurRec = &CurMultiClass->Rec;
      74             : 
      75   207254058 :   if (RecordVal *ERV = CurRec->getValue(RV.getNameInit())) {
      76             :     // The value already exists in the class, treat this as a set.
      77     9778396 :     if (ERV->setValue(RV.getValue()))
      78           0 :       return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
      79           0 :                    RV.getType()->getAsString() + "' is incompatible with " +
      80           0 :                    "previous definition of type '" +
      81           0 :                    ERV->getType()->getAsString() + "'");
      82             :   } else {
      83    98737831 :     CurRec->addValue(RV);
      84             :   }
      85             :   return false;
      86             : }
      87             : 
      88             : /// SetValue -
      89             : /// Return true on error, false on success.
      90    12859754 : bool TGParser::SetValue(Record *CurRec, SMLoc Loc, Init *ValName,
      91             :                         ArrayRef<unsigned> BitList, Init *V,
      92             :                         bool AllowSelfAssignment) {
      93    12859754 :   if (!V) return false;
      94             : 
      95    12859754 :   if (!CurRec) CurRec = &CurMultiClass->Rec;
      96             : 
      97             :   RecordVal *RV = CurRec->getValue(ValName);
      98    12859754 :   if (!RV)
      99           0 :     return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
     100             :                  "' unknown!");
     101             : 
     102             :   // Do not allow assignments like 'X = X'.  This will just cause infinite loops
     103             :   // in the resolution machinery.
     104    12859754 :   if (BitList.empty())
     105             :     if (VarInit *VI = dyn_cast<VarInit>(V))
     106      642618 :       if (VI->getNameInit() == ValName && !AllowSelfAssignment)
     107           0 :         return Error(Loc, "Recursion / self-assignment forbidden");
     108             : 
     109             :   // If we are assigning to a subset of the bits in the value... then we must be
     110             :   // assigning to a field of BitsRecTy, which must have a BitsInit
     111             :   // initializer.
     112             :   //
     113    12859754 :   if (!BitList.empty()) {
     114      184104 :     BitsInit *CurVal = dyn_cast<BitsInit>(RV->getValue());
     115             :     if (!CurVal)
     116           0 :       return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
     117             :                    "' is not a bits type");
     118             : 
     119             :     // Convert the incoming value to a bits type of the appropriate size...
     120      184104 :     Init *BI = V->convertInitializerTo(BitsRecTy::get(BitList.size()));
     121      184104 :     if (!BI)
     122           0 :       return Error(Loc, "Initializer is not compatible with bit range");
     123             : 
     124             :     // We should have a BitsInit type now.
     125             :     BitsInit *BInit = cast<BitsInit>(BI);
     126             : 
     127      368208 :     SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
     128             : 
     129             :     // Loop over bits, assigning values as appropriate.
     130     1894884 :     for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
     131     1710780 :       unsigned Bit = BitList[i];
     132     1710780 :       if (NewBits[Bit])
     133           0 :         return Error(Loc, "Cannot set bit #" + Twine(Bit) + " of value '" +
     134           0 :                      ValName->getAsUnquotedString() + "' more than once");
     135      855390 :       NewBits[Bit] = BInit->getBit(i);
     136             :     }
     137             : 
     138     6307292 :     for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
     139    12246376 :       if (!NewBits[i])
     140     5267798 :         NewBits[i] = CurVal->getBit(i);
     141             : 
     142      184104 :     V = BitsInit::get(NewBits);
     143             :   }
     144             : 
     145    12859754 :   if (RV->setValue(V)) {
     146             :     std::string InitType;
     147             :     if (BitsInit *BI = dyn_cast<BitsInit>(V))
     148          16 :       InitType = (Twine("' of type bit initializer with length ") +
     149          32 :                   Twine(BI->getNumBits())).str();
     150             :     else if (TypedInit *TI = dyn_cast<TypedInit>(V))
     151           4 :       InitType = (Twine("' of type '") + TI->getType()->getAsString()).str();
     152          45 :     return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
     153          45 :                           "' of type '" + RV->getType()->getAsString() +
     154          18 :                           "' is incompatible with initializer '" +
     155          45 :                           V->getAsString() + InitType + "'");
     156             :   }
     157             :   return false;
     158             : }
     159             : 
     160             : /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
     161             : /// args as SubClass's template arguments.
     162     4129561 : bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
     163     4129561 :   Record *SC = SubClass.Rec;
     164             :   // Add all of the values in the subclass into the current class.
     165   210172689 :   for (const RecordVal &Val : SC->getValues())
     166   103021564 :     if (AddValue(CurRec, SubClass.RefRange.Start, Val))
     167             :       return true;
     168             : 
     169             :   ArrayRef<Init *> TArgs = SC->getTemplateArgs();
     170             : 
     171             :   // Ensure that an appropriate number of template arguments are specified.
     172     4129561 :   if (TArgs.size() < SubClass.TemplateArgs.size())
     173           0 :     return Error(SubClass.RefRange.Start,
     174             :                  "More template args specified than expected");
     175             : 
     176             :   // Loop over all of the template arguments, setting them to the specified
     177             :   // value or leaving them as the default if necessary.
     178    12035682 :   for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
     179    15812242 :     if (i < SubClass.TemplateArgs.size()) {
     180             :       // If a value is specified for this template arg, set it now.
     181    12657112 :       if (SetValue(CurRec, SubClass.RefRange.Start, TArgs[i],
     182             :                    None, SubClass.TemplateArgs[i]))
     183             :         return true;
     184             : 
     185             :       // Resolve it next.
     186    12657112 :       CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
     187             : 
     188             :       // Now remove it.
     189     6328556 :       CurRec->removeValue(TArgs[i]);
     190             : 
     191     3155130 :     } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
     192             :       return Error(SubClass.RefRange.Start,
     193           0 :                    "Value not specified for template argument #" +
     194           0 :                    Twine(i) + " (" + TArgs[i]->getAsUnquotedString() +
     195           0 :                    ") of subclass '" + SC->getNameInitAsString() + "'!");
     196             :     }
     197             :   }
     198             : 
     199             :   // Since everything went well, we can now set the "superclass" list for the
     200             :   // current record.
     201             :   ArrayRef<std::pair<Record *, SMRange>> SCs = SC->getSuperClasses();
     202    24894615 :   for (const auto &SCPair : SCs) {
     203    20765054 :     if (CurRec->isSubClassOf(SCPair.first))
     204             :       return Error(SubClass.RefRange.Start,
     205           0 :                    "Already subclass of '" + SCPair.first->getName() + "'!\n");
     206             :     CurRec->addSuperClass(SCPair.first, SCPair.second);
     207             :   }
     208             : 
     209     4129561 :   if (CurRec->isSubClassOf(SC))
     210             :     return Error(SubClass.RefRange.Start,
     211           0 :                  "Already subclass of '" + SC->getName() + "'!\n");
     212             :   CurRec->addSuperClass(SC, SubClass.RefRange);
     213     4129561 :   return false;
     214             : }
     215             : 
     216             : /// AddSubMultiClass - Add SubMultiClass as a subclass to
     217             : /// CurMC, resolving its template args as SubMultiClass's
     218             : /// template arguments.
     219        1822 : bool TGParser::AddSubMultiClass(MultiClass *CurMC,
     220             :                                 SubMultiClassReference &SubMultiClass) {
     221        1822 :   MultiClass *SMC = SubMultiClass.MC;
     222        1822 :   Record *CurRec = &CurMC->Rec;
     223             : 
     224             :   // Add all of the values in the subclass into the current class.
     225       20634 :   for (const auto &SMCVal : SMC->Rec.getValues())
     226        9406 :     if (AddValue(CurRec, SubMultiClass.RefRange.Start, SMCVal))
     227             :       return true;
     228             : 
     229        1822 :   unsigned newDefStart = CurMC->DefPrototypes.size();
     230             : 
     231             :   // Add all of the defs in the subclass into the current multiclass.
     232       13113 :   for (const std::unique_ptr<Record> &R : SMC->DefPrototypes) {
     233             :     // Clone the def and add it to the current multiclass
     234       11291 :     auto NewDef = make_unique<Record>(*R);
     235             : 
     236             :     // Add all of the values in the superclass into the current def.
     237      223933 :     for (const auto &MCVal : CurRec->getValues())
     238      106321 :       if (AddValue(NewDef.get(), SubMultiClass.RefRange.Start, MCVal))
     239           0 :         return true;
     240             : 
     241       11291 :     CurMC->DefPrototypes.push_back(std::move(NewDef));
     242             :   }
     243             : 
     244             :   ArrayRef<Init *> SMCTArgs = SMC->Rec.getTemplateArgs();
     245             : 
     246             :   // Ensure that an appropriate number of template arguments are
     247             :   // specified.
     248        1822 :   if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
     249           0 :     return Error(SubMultiClass.RefRange.Start,
     250             :                  "More template args specified than expected");
     251             : 
     252             :   // Loop over all of the template arguments, setting them to the specified
     253             :   // value or leaving them as the default if necessary.
     254        9406 :   for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
     255       15168 :     if (i < SubMultiClass.TemplateArgs.size()) {
     256             :       // If a value is specified for this template arg, set it in the
     257             :       // superclass now.
     258       15020 :       if (SetValue(CurRec, SubMultiClass.RefRange.Start, SMCTArgs[i],
     259             :                    None, SubMultiClass.TemplateArgs[i]))
     260             :         return true;
     261             : 
     262             :       // Resolve it next.
     263       15020 :       CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i]));
     264             : 
     265             :       // Now remove it.
     266        7510 :       CurRec->removeValue(SMCTArgs[i]);
     267             : 
     268             :       // If a value is specified for this template arg, set it in the
     269             :       // new defs now.
     270       51133 :       for (const auto &Def :
     271       66153 :              makeArrayRef(CurMC->DefPrototypes).slice(newDefStart)) {
     272      153399 :         if (SetValue(Def.get(), SubMultiClass.RefRange.Start, SMCTArgs[i],
     273             :                      None, SubMultiClass.TemplateArgs[i]))
     274             :           return true;
     275             : 
     276             :         // Resolve it next.
     277      102266 :         Def->resolveReferencesTo(Def->getValue(SMCTArgs[i]));
     278             : 
     279             :         // Now remove it
     280       51133 :         Def->removeValue(SMCTArgs[i]);
     281             :       }
     282         148 :     } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
     283             :       return Error(SubMultiClass.RefRange.Start,
     284           0 :                    "Value not specified for template argument #" +
     285           0 :                    Twine(i) + " (" + SMCTArgs[i]->getAsUnquotedString() +
     286           0 :                    ") of subclass '" + SMC->Rec.getNameInitAsString() + "'!");
     287             :     }
     288             :   }
     289             : 
     290             :   return false;
     291             : }
     292             : 
     293             : /// ProcessForeachDefs - Given a record, apply all of the variable
     294             : /// values in all surrounding foreach loops, creating new records for
     295             : /// each combination of values.
     296     1962628 : bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc) {
     297     1962628 :   if (Loops.empty())
     298             :     return false;
     299             : 
     300             :   // We want to instantiate a new copy of CurRec for each combination
     301             :   // of nested loop iterator values.  We don't want top instantiate
     302             :   // any copies until we have values for each loop iterator.
     303             :   IterSet IterVals;
     304        2252 :   return ProcessForeachDefs(CurRec, Loc, IterVals);
     305             : }
     306             : 
     307             : /// ProcessForeachDefs - Given a record, a loop and a loop iterator,
     308             : /// apply each of the variable values in this loop and then process
     309             : /// subloops.
     310       59403 : bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc, IterSet &IterVals){
     311             :   // Recursively build a tuple of iterator values.
     312      178209 :   if (IterVals.size() != Loops.size()) {
     313             :     assert(IterVals.size() < Loops.size());
     314             :     ForeachLoop &CurLoop = Loops[IterVals.size()];
     315        6508 :     ListInit *List = dyn_cast<ListInit>(CurLoop.ListValue);
     316        6508 :     if (!List) {
     317           0 :       Error(Loc, "Loop list is not a list");
     318           0 :       return true;
     319             :     }
     320             : 
     321             :     // Process each value.
     322      120810 :     for (unsigned i = 0; i < List->size(); ++i) {
     323       57151 :       Init *ItemVal = List->resolveListElementReference(*CurRec, nullptr, i);
     324      114302 :       IterVals.push_back(IterRecord(CurLoop.IterVar, ItemVal));
     325       57151 :       if (ProcessForeachDefs(CurRec, Loc, IterVals))
     326             :         return true;
     327             :       IterVals.pop_back();
     328             :     }
     329             :     return false;
     330             :   }
     331             : 
     332             :   // This is the bottom of the recursion. We have all of the iterator values
     333             :   // for this point in the iteration space.  Instantiate a new record to
     334             :   // reflect this combination of values.
     335       52895 :   auto IterRec = make_unique<Record>(*CurRec);
     336             : 
     337             :   // Set the iterator values now.
     338      122768 :   for (IterRecord &IR : IterVals) {
     339       69873 :     VarInit *IterVar = IR.IterVar;
     340       69873 :     TypedInit *IVal = dyn_cast<TypedInit>(IR.IterValue);
     341             :     if (!IVal)
     342           0 :       return Error(Loc, "foreach iterator value is untyped");
     343             : 
     344       69873 :     IterRec->addValue(RecordVal(IterVar->getNameInit(), IVal->getType(), false));
     345             : 
     346      139746 :     if (SetValue(IterRec.get(), Loc, IterVar->getNameInit(), None, IVal))
     347           0 :       return Error(Loc, "when instantiating this def");
     348             : 
     349             :     // Resolve it next.
     350      139746 :     IterRec->resolveReferencesTo(IterRec->getValue(IterVar->getNameInit()));
     351             : 
     352             :     // Remove it.
     353       69873 :     IterRec->removeValue(IterVar->getNameInit());
     354             :   }
     355             : 
     356      158685 :   if (Records.getDef(IterRec->getNameInitAsString())) {
     357             :     // If this record is anonymous, it's no problem, just generate a new name
     358         847 :     if (!IterRec->isAnonymous())
     359           0 :       return Error(Loc, "def already exists: " +IterRec->getNameInitAsString());
     360             : 
     361         847 :     IterRec->setName(GetNewAnonymousName());
     362             :   }
     363             : 
     364             :   Record *IterRecSave = IterRec.get(); // Keep a copy before release.
     365      105790 :   Records.addDef(std::move(IterRec));
     366             :   IterRecSave->resolveReferences();
     367       52895 :   return false;
     368             : }
     369             : 
     370             : //===----------------------------------------------------------------------===//
     371             : // Parser Code
     372             : //===----------------------------------------------------------------------===//
     373             : 
     374             : /// isObjectStart - Return true if this is a valid first token for an Object.
     375             : static bool isObjectStart(tgtok::TokKind K) {
     376     2325302 :   return K == tgtok::Class || K == tgtok::Def ||
     377      270664 :          K == tgtok::Defm || K == tgtok::Let ||
     378     2413981 :          K == tgtok::MultiClass || K == tgtok::Foreach;
     379             : }
     380             : 
     381             : /// GetNewAnonymousName - Generate a unique anonymous name that can be used as
     382             : /// an identifier.
     383      720060 : Init *TGParser::GetNewAnonymousName() {
     384     2880240 :   return StringInit::get("anonymous_" + utostr(AnonCounter++));
     385             : }
     386             : 
     387             : /// ParseObjectName - If an object name is specified, return it.  Otherwise,
     388             : /// return 0.
     389             : ///   ObjectName ::= Value [ '#' Value ]*
     390             : ///   ObjectName ::= /*empty*/
     391             : ///
     392     2056897 : Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
     393     2056897 :   switch (Lex.getCode()) {
     394             :   case tgtok::colon:
     395             :   case tgtok::semi:
     396             :   case tgtok::l_brace:
     397             :     // These are all of the tokens that can begin an object body.
     398             :     // Some of these can also begin values but we disallow those cases
     399             :     // because they are unlikely to be useful.
     400             :     return nullptr;
     401             :   default:
     402             :     break;
     403             :   }
     404             : 
     405             :   Record *CurRec = nullptr;
     406     1639340 :   if (CurMultiClass)
     407       61865 :     CurRec = &CurMultiClass->Rec;
     408             : 
     409             :   RecTy *Type = nullptr;
     410             :   if (CurRec) {
     411       61865 :     const TypedInit *CurRecName = dyn_cast<TypedInit>(CurRec->getNameInit());
     412             :     if (!CurRecName) {
     413           0 :       TokError("Record name is not typed!");
     414           0 :       return nullptr;
     415             :     }
     416       61865 :     Type = CurRecName->getType();
     417             :   }
     418             : 
     419     1639340 :   return ParseValue(CurRec, Type, ParseNameMode);
     420             : }
     421             : 
     422             : /// ParseClassID - Parse and resolve a reference to a class name.  This returns
     423             : /// null on error.
     424             : ///
     425             : ///    ClassID ::= ID
     426             : ///
     427     2984767 : Record *TGParser::ParseClassID() {
     428     2984767 :   if (Lex.getCode() != tgtok::Id) {
     429           0 :     TokError("expected name for ClassID");
     430           0 :     return nullptr;
     431             :   }
     432             : 
     433     5969534 :   Record *Result = Records.getClass(Lex.getCurStrVal());
     434     2984767 :   if (!Result)
     435           0 :     TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
     436             : 
     437     2984767 :   Lex.Lex();
     438     2984767 :   return Result;
     439             : }
     440             : 
     441             : /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
     442             : /// This returns null on error.
     443             : ///
     444             : ///    MultiClassID ::= ID
     445             : ///
     446      124876 : MultiClass *TGParser::ParseMultiClassID() {
     447      124876 :   if (Lex.getCode() != tgtok::Id) {
     448           0 :     TokError("expected name for MultiClassID");
     449           0 :     return nullptr;
     450             :   }
     451             : 
     452      124876 :   MultiClass *Result = MultiClasses[Lex.getCurStrVal()].get();
     453      124876 :   if (!Result)
     454           0 :     TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
     455             : 
     456      124876 :   Lex.Lex();
     457      124876 :   return Result;
     458             : }
     459             : 
     460             : /// ParseSubClassReference - Parse a reference to a subclass or to a templated
     461             : /// subclass.  This returns a SubClassRefTy with a null Record* on error.
     462             : ///
     463             : ///  SubClassRef ::= ClassID
     464             : ///  SubClassRef ::= ClassID '<' ValueList '>'
     465             : ///
     466     2945279 : SubClassReference TGParser::
     467             : ParseSubClassReference(Record *CurRec, bool isDefm) {
     468             :   SubClassReference Result;
     469     2945279 :   Result.RefRange.Start = Lex.getLoc();
     470             : 
     471     2945279 :   if (isDefm) {
     472      123054 :     if (MultiClass *MC = ParseMultiClassID())
     473      123054 :       Result.Rec = &MC->Rec;
     474             :   } else {
     475     2822225 :     Result.Rec = ParseClassID();
     476             :   }
     477     2945279 :   if (!Result.Rec) return Result;
     478             : 
     479             :   // If there is no template arg list, we're done.
     480     2945279 :   if (Lex.getCode() != tgtok::less) {
     481      291924 :     Result.RefRange.End = Lex.getLoc();
     482      291924 :     return Result;
     483             :   }
     484             :   Lex.Lex();  // Eat the '<'
     485             : 
     486     2653355 :   if (Lex.getCode() == tgtok::greater) {
     487           0 :     TokError("subclass reference requires a non-empty list of template values");
     488           0 :     Result.Rec = nullptr;
     489           0 :     return Result;
     490             :   }
     491             : 
     492     2653355 :   ParseValueList(Result.TemplateArgs, CurRec, Result.Rec);
     493     2653355 :   if (Result.TemplateArgs.empty()) {
     494           0 :     Result.Rec = nullptr;   // Error parsing value list.
     495           0 :     return Result;
     496             :   }
     497             : 
     498     2653355 :   if (Lex.getCode() != tgtok::greater) {
     499           0 :     TokError("expected '>' in template value list");
     500           0 :     Result.Rec = nullptr;
     501           0 :     return Result;
     502             :   }
     503             :   Lex.Lex();
     504     2653355 :   Result.RefRange.End = Lex.getLoc();
     505             : 
     506     2653355 :   return Result;
     507             : }
     508             : 
     509             : /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
     510             : /// templated submulticlass.  This returns a SubMultiClassRefTy with a null
     511             : /// Record* on error.
     512             : ///
     513             : ///  SubMultiClassRef ::= MultiClassID
     514             : ///  SubMultiClassRef ::= MultiClassID '<' ValueList '>'
     515             : ///
     516        1822 : SubMultiClassReference TGParser::
     517             : ParseSubMultiClassReference(MultiClass *CurMC) {
     518             :   SubMultiClassReference Result;
     519        1822 :   Result.RefRange.Start = Lex.getLoc();
     520             : 
     521        1822 :   Result.MC = ParseMultiClassID();
     522        1822 :   if (!Result.MC) return Result;
     523             : 
     524             :   // If there is no template arg list, we're done.
     525        1822 :   if (Lex.getCode() != tgtok::less) {
     526           0 :     Result.RefRange.End = Lex.getLoc();
     527           0 :     return Result;
     528             :   }
     529             :   Lex.Lex();  // Eat the '<'
     530             : 
     531        1822 :   if (Lex.getCode() == tgtok::greater) {
     532           0 :     TokError("subclass reference requires a non-empty list of template values");
     533           0 :     Result.MC = nullptr;
     534           0 :     return Result;
     535             :   }
     536             : 
     537        1822 :   ParseValueList(Result.TemplateArgs, &CurMC->Rec, &Result.MC->Rec);
     538        1822 :   if (Result.TemplateArgs.empty()) {
     539           0 :     Result.MC = nullptr;   // Error parsing value list.
     540           0 :     return Result;
     541             :   }
     542             : 
     543        1822 :   if (Lex.getCode() != tgtok::greater) {
     544           0 :     TokError("expected '>' in template value list");
     545           0 :     Result.MC = nullptr;
     546           0 :     return Result;
     547             :   }
     548             :   Lex.Lex();
     549        1822 :   Result.RefRange.End = Lex.getLoc();
     550             : 
     551        1822 :   return Result;
     552             : }
     553             : 
     554             : /// ParseRangePiece - Parse a bit/value range.
     555             : ///   RangePiece ::= INTVAL
     556             : ///   RangePiece ::= INTVAL '-' INTVAL
     557             : ///   RangePiece ::= INTVAL INTVAL
     558      229947 : bool TGParser::ParseRangePiece(SmallVectorImpl<unsigned> &Ranges) {
     559      229947 :   if (Lex.getCode() != tgtok::IntVal) {
     560           0 :     TokError("expected integer or bitrange");
     561           0 :     return true;
     562             :   }
     563      229947 :   int64_t Start = Lex.getCurIntVal();
     564             :   int64_t End;
     565             : 
     566      229947 :   if (Start < 0)
     567           0 :     return TokError("invalid range, cannot be negative");
     568             : 
     569      459894 :   switch (Lex.Lex()) {  // eat first character.
     570       44794 :   default:
     571       44794 :     Ranges.push_back(Start);
     572       44794 :     return false;
     573         450 :   case tgtok::minus:
     574         450 :     if (Lex.Lex() != tgtok::IntVal) {
     575           0 :       TokError("expected integer value as end of range");
     576           0 :       return true;
     577             :     }
     578         450 :     End = Lex.getCurIntVal();
     579         450 :     break;
     580      184703 :   case tgtok::IntVal:
     581      184703 :     End = -Lex.getCurIntVal();
     582      184703 :     break;
     583             :   }
     584      185153 :   if (End < 0)
     585           0 :     return TokError("invalid range, cannot be negative");
     586             :   Lex.Lex();
     587             : 
     588             :   // Add to the range.
     589      185153 :   if (Start < End)
     590      124121 :     for (; Start <= End; ++Start)
     591       58897 :       Ranges.push_back(Start);
     592             :   else
     593     2062610 :     for (; Start >= End; --Start)
     594      941892 :       Ranges.push_back(Start);
     595             :   return false;
     596             : }
     597             : 
     598             : /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
     599             : ///
     600             : ///   RangeList ::= RangePiece (',' RangePiece)*
     601             : ///
     602      228238 : void TGParser::ParseRangeList(SmallVectorImpl<unsigned> &Result) {
     603             :   // Parse the first piece.
     604      228238 :   if (ParseRangePiece(Result)) {
     605             :     Result.clear();
     606             :     return;
     607             :   }
     608      229074 :   while (Lex.getCode() == tgtok::comma) {
     609         836 :     Lex.Lex();  // Eat the comma.
     610             : 
     611             :     // Parse the next range piece.
     612         836 :     if (ParseRangePiece(Result)) {
     613             :       Result.clear();
     614             :       return;
     615             :     }
     616             :   }
     617             : }
     618             : 
     619             : /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
     620             : ///   OptionalRangeList ::= '<' RangeList '>'
     621             : ///   OptionalRangeList ::= /*empty*/
     622      113972 : bool TGParser::ParseOptionalRangeList(SmallVectorImpl<unsigned> &Ranges) {
     623      113972 :   if (Lex.getCode() != tgtok::less)
     624             :     return false;
     625             : 
     626           0 :   SMLoc StartLoc = Lex.getLoc();
     627             :   Lex.Lex(); // eat the '<'
     628             : 
     629             :   // Parse the range list.
     630           0 :   ParseRangeList(Ranges);
     631           0 :   if (Ranges.empty()) return true;
     632             : 
     633           0 :   if (Lex.getCode() != tgtok::greater) {
     634           0 :     TokError("expected '>' at end of range list");
     635           0 :     return Error(StartLoc, "to match this '<'");
     636             :   }
     637             :   Lex.Lex();   // eat the '>'.
     638           0 :   return false;
     639             : }
     640             : 
     641             : /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
     642             : ///   OptionalBitList ::= '{' RangeList '}'
     643             : ///   OptionalBitList ::= /*empty*/
     644      635413 : bool TGParser::ParseOptionalBitList(SmallVectorImpl<unsigned> &Ranges) {
     645      635413 :   if (Lex.getCode() != tgtok::l_brace)
     646             :     return false;
     647             : 
     648      184104 :   SMLoc StartLoc = Lex.getLoc();
     649             :   Lex.Lex(); // eat the '{'
     650             : 
     651             :   // Parse the range list.
     652      184104 :   ParseRangeList(Ranges);
     653      184104 :   if (Ranges.empty()) return true;
     654             : 
     655      184104 :   if (Lex.getCode() != tgtok::r_brace) {
     656           0 :     TokError("expected '}' at end of bit list");
     657           0 :     return Error(StartLoc, "to match this '{'");
     658             :   }
     659             :   Lex.Lex();   // eat the '}'.
     660      184104 :   return false;
     661             : }
     662             : 
     663             : /// ParseType - Parse and return a tblgen type.  This returns null on error.
     664             : ///
     665             : ///   Type ::= STRING                       // string type
     666             : ///   Type ::= CODE                         // code type
     667             : ///   Type ::= BIT                          // bit type
     668             : ///   Type ::= BITS '<' INTVAL '>'          // bits<x> type
     669             : ///   Type ::= INT                          // int type
     670             : ///   Type ::= LIST '<' Type '>'            // list<x> type
     671             : ///   Type ::= DAG                          // dag type
     672             : ///   Type ::= ClassID                      // Record Type
     673             : ///
     674      550392 : RecTy *TGParser::ParseType() {
     675      550392 :   switch (Lex.getCode()) {
     676           0 :   default: TokError("Unknown token when expecting a type"); return nullptr;
     677      256968 :   case tgtok::String: Lex.Lex(); return StringRecTy::get();
     678        5902 :   case tgtok::Code:   Lex.Lex(); return CodeRecTy::get();
     679       74312 :   case tgtok::Bit:    Lex.Lex(); return BitRecTy::get();
     680       51926 :   case tgtok::Int:    Lex.Lex(); return IntRecTy::get();
     681       96560 :   case tgtok::Dag:    Lex.Lex(); return DagRecTy::get();
     682      162542 :   case tgtok::Id:
     683      162542 :     if (Record *R = ParseClassID()) return RecordRecTy::get(R);
     684             :     return nullptr;
     685      104715 :   case tgtok::Bits: {
     686      209430 :     if (Lex.Lex() != tgtok::less) { // Eat 'bits'
     687           0 :       TokError("expected '<' after bits type");
     688           0 :       return nullptr;
     689             :     }
     690      104715 :     if (Lex.Lex() != tgtok::IntVal) {  // Eat '<'
     691           0 :       TokError("expected integer in bits<n> type");
     692           0 :       return nullptr;
     693             :     }
     694      104715 :     uint64_t Val = Lex.getCurIntVal();
     695      104715 :     if (Lex.Lex() != tgtok::greater) {  // Eat count.
     696           0 :       TokError("expected '>' at end of bits<n> type");
     697           0 :       return nullptr;
     698             :     }
     699             :     Lex.Lex();  // Eat '>'
     700      104715 :     return BitsRecTy::get(Val);
     701             :   }
     702       40301 :   case tgtok::List: {
     703       80602 :     if (Lex.Lex() != tgtok::less) { // Eat 'bits'
     704           0 :       TokError("expected '<' after list type");
     705           0 :       return nullptr;
     706             :     }
     707             :     Lex.Lex();  // Eat '<'
     708       40301 :     RecTy *SubType = ParseType();
     709       40301 :     if (!SubType) return nullptr;
     710             : 
     711       40301 :     if (Lex.getCode() != tgtok::greater) {
     712           0 :       TokError("expected '>' at end of list<ty> type");
     713           0 :       return nullptr;
     714             :     }
     715             :     Lex.Lex();  // Eat '>'
     716       40301 :     return ListRecTy::get(SubType);
     717             :   }
     718             :   }
     719             : }
     720             : 
     721             : /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
     722             : /// has already been read.
     723     9100616 : Init *TGParser::ParseIDValue(Record *CurRec, StringInit *Name, SMLoc NameLoc,
     724             :                              IDParseMode Mode) {
     725     9100616 :   if (CurRec) {
     726     7136229 :     if (const RecordVal *RV = CurRec->getValue(Name))
     727      101178 :       return VarInit::get(Name, RV->getType());
     728             : 
     729     7035051 :     Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
     730             : 
     731     7035051 :     if (CurMultiClass)
     732      587705 :       TemplateArgName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
     733             :                                     "::");
     734             : 
     735     7035051 :     if (CurRec->isTemplateArg(TemplateArgName)) {
     736             :       const RecordVal *RV = CurRec->getValue(TemplateArgName);
     737             :       assert(RV && "Template arg doesn't exist??");
     738      307627 :       return VarInit::get(TemplateArgName, RV->getType());
     739             :     }
     740             :   }
     741             : 
     742     8691811 :   if (CurMultiClass) {
     743      703343 :     Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::");
     744             : 
     745     1406686 :     if (CurMultiClass->Rec.isTemplateArg(MCName)) {
     746             :       const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
     747             :       assert(RV && "Template arg doesn't exist??");
     748      298824 :       return VarInit::get(MCName, RV->getType());
     749             :     }
     750             :   }
     751             : 
     752             :   // If this is in a foreach loop, make sure it's not a loop iterator
     753     8399205 :   for (const auto &L : Loops) {
     754       12921 :     VarInit *IterVar = dyn_cast<VarInit>(L.IterVar);
     755       12921 :     if (IterVar && IterVar->getNameInit() == Name)
     756             :       return IterVar;
     757             :   }
     758             : 
     759     8386284 :   if (Mode == ParseNameMode)
     760             :     return Name;
     761             : 
     762     6742780 :   if (Record *D = Records.getDef(Name->getValue()))
     763     6742780 :     return DefInit::get(D);
     764             : 
     765           0 :   if (Mode == ParseValueMode) {
     766           0 :     Error(NameLoc, "Variable not defined: '" + Name->getValue() + "'");
     767           0 :     return nullptr;
     768             :   }
     769             : 
     770             :   return Name;
     771             : }
     772             : 
     773             : /// ParseOperation - Parse an operator.  This returns null on error.
     774             : ///
     775             : /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
     776             : ///
     777       62700 : Init *TGParser::ParseOperation(Record *CurRec, RecTy *ItemType) {
     778       62700 :   switch (Lex.getCode()) {
     779             :   default:
     780           0 :     TokError("unknown operation");
     781           0 :     return nullptr;
     782       20509 :   case tgtok::XHead:
     783             :   case tgtok::XTail:
     784             :   case tgtok::XEmpty:
     785             :   case tgtok::XCast: {  // Value ::= !unop '(' Value ')'
     786             :     UnOpInit::UnaryOp Code;
     787             :     RecTy *Type = nullptr;
     788             : 
     789       20509 :     switch (Lex.getCode()) {
     790           0 :     default: llvm_unreachable("Unhandled code!");
     791       20249 :     case tgtok::XCast:
     792       20249 :       Lex.Lex();  // eat the operation
     793             :       Code = UnOpInit::CAST;
     794             : 
     795       20249 :       Type = ParseOperatorType();
     796             : 
     797       20249 :       if (!Type) {
     798           0 :         TokError("did not get type for unary operator");
     799           0 :         return nullptr;
     800             :       }
     801             : 
     802             :       break;
     803          69 :     case tgtok::XHead:
     804          69 :       Lex.Lex();  // eat the operation
     805             :       Code = UnOpInit::HEAD;
     806          69 :       break;
     807           7 :     case tgtok::XTail:
     808           7 :       Lex.Lex();  // eat the operation
     809             :       Code = UnOpInit::TAIL;
     810           7 :       break;
     811         184 :     case tgtok::XEmpty:
     812         184 :       Lex.Lex();  // eat the operation
     813             :       Code = UnOpInit::EMPTY;
     814             :       Type = IntRecTy::get();
     815         184 :       break;
     816             :     }
     817       20509 :     if (Lex.getCode() != tgtok::l_paren) {
     818           0 :       TokError("expected '(' after unary operator");
     819           0 :       return nullptr;
     820             :     }
     821       20509 :     Lex.Lex();  // eat the '('
     822             : 
     823       20509 :     Init *LHS = ParseValue(CurRec);
     824       20509 :     if (!LHS) return nullptr;
     825             : 
     826       20509 :     if (Code == UnOpInit::HEAD ||
     827       20509 :         Code == UnOpInit::TAIL ||
     828             :         Code == UnOpInit::EMPTY) {
     829             :       ListInit *LHSl = dyn_cast<ListInit>(LHS);
     830             :       StringInit *LHSs = dyn_cast<StringInit>(LHS);
     831             :       TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
     832         260 :       if (!LHSl && !LHSs && !LHSt) {
     833           0 :         TokError("expected list or string type argument in unary operator");
     834           0 :         return nullptr;
     835             :       }
     836         260 :       if (LHSt) {
     837         260 :         ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
     838             :         StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
     839         260 :         if (!LType && !SType) {
     840           0 :           TokError("expected list or string type argument in unary operator");
     841           0 :           return nullptr;
     842             :         }
     843             :       }
     844             : 
     845         260 :       if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL) {
     846          76 :         if (!LHSl && !LHSt) {
     847           0 :           TokError("expected list type argument in unary operator");
     848           0 :           return nullptr;
     849             :         }
     850             : 
     851          76 :         if (LHSl && LHSl->empty()) {
     852           0 :           TokError("empty list argument in unary operator");
     853           0 :           return nullptr;
     854             :         }
     855          76 :         if (LHSl) {
     856             :           Init *Item = LHSl->getElement(0);
     857             :           TypedInit *Itemt = dyn_cast<TypedInit>(Item);
     858             :           if (!Itemt) {
     859           0 :             TokError("untyped list element in unary operator");
     860           0 :             return nullptr;
     861             :           }
     862           0 :           Type = (Code == UnOpInit::HEAD) ? Itemt->getType()
     863           0 :                                           : ListRecTy::get(Itemt->getType());
     864             :         } else {
     865             :           assert(LHSt && "expected list type argument in unary operator");
     866          76 :           ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
     867             :           if (!LType) {
     868           0 :             TokError("expected list type argument in unary operator");
     869           0 :             return nullptr;
     870             :           }
     871          76 :           Type = (Code == UnOpInit::HEAD) ? LType->getElementType() : LType;
     872             :         }
     873             :       }
     874             :     }
     875             : 
     876       20509 :     if (Lex.getCode() != tgtok::r_paren) {
     877           0 :       TokError("expected ')' in unary operator");
     878           0 :       return nullptr;
     879             :     }
     880             :     Lex.Lex();  // eat the ')'
     881       20509 :     return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
     882             :   }
     883             : 
     884       29690 :   case tgtok::XConcat:
     885             :   case tgtok::XADD:
     886             :   case tgtok::XAND:
     887             :   case tgtok::XOR:
     888             :   case tgtok::XSRA:
     889             :   case tgtok::XSRL:
     890             :   case tgtok::XSHL:
     891             :   case tgtok::XEq:
     892             :   case tgtok::XListConcat:
     893             :   case tgtok::XStrConcat: {  // Value ::= !binop '(' Value ',' Value ')'
     894             :     tgtok::TokKind OpTok = Lex.getCode();
     895       29690 :     SMLoc OpLoc = Lex.getLoc();
     896             :     Lex.Lex();  // eat the operation
     897             : 
     898             :     BinOpInit::BinaryOp Code;
     899             :     RecTy *Type = nullptr;
     900             : 
     901       29690 :     switch (OpTok) {
     902           0 :     default: llvm_unreachable("Unhandled code!");
     903             :     case tgtok::XConcat: Code = BinOpInit::CONCAT;Type = DagRecTy::get(); break;
     904        1374 :     case tgtok::XADD:    Code = BinOpInit::ADD;   Type = IntRecTy::get(); break;
     905         204 :     case tgtok::XAND:    Code = BinOpInit::AND;   Type = IntRecTy::get(); break;
     906          67 :     case tgtok::XOR:     Code = BinOpInit::OR;    Type = IntRecTy::get(); break;
     907           0 :     case tgtok::XSRA:    Code = BinOpInit::SRA;   Type = IntRecTy::get(); break;
     908         118 :     case tgtok::XSRL:    Code = BinOpInit::SRL;   Type = IntRecTy::get(); break;
     909         165 :     case tgtok::XSHL:    Code = BinOpInit::SHL;   Type = IntRecTy::get(); break;
     910        5273 :     case tgtok::XEq:     Code = BinOpInit::EQ;    Type = BitRecTy::get(); break;
     911         468 :     case tgtok::XListConcat:
     912             :       Code = BinOpInit::LISTCONCAT;
     913             :       // We don't know the list type until we parse the first argument
     914         468 :       break;
     915       21429 :     case tgtok::XStrConcat:
     916             :       Code = BinOpInit::STRCONCAT;
     917             :       Type = StringRecTy::get();
     918       21429 :       break;
     919             :     }
     920             : 
     921       29690 :     if (Lex.getCode() != tgtok::l_paren) {
     922           0 :       TokError("expected '(' after binary operator");
     923           0 :       return nullptr;
     924             :     }
     925             :     Lex.Lex();  // eat the '('
     926             : 
     927             :     SmallVector<Init*, 2> InitList;
     928             : 
     929       29690 :     InitList.push_back(ParseValue(CurRec));
     930       29690 :     if (!InitList.back()) return nullptr;
     931             : 
     932       63430 :     while (Lex.getCode() == tgtok::comma) {
     933             :       Lex.Lex();  // eat the ','
     934             : 
     935       33740 :       InitList.push_back(ParseValue(CurRec));
     936       33740 :       if (!InitList.back()) return nullptr;
     937             :     }
     938             : 
     939       29690 :     if (Lex.getCode() != tgtok::r_paren) {
     940           0 :       TokError("expected ')' in operator");
     941           0 :       return nullptr;
     942             :     }
     943             :     Lex.Lex();  // eat the ')'
     944             : 
     945             :     // If we are doing !listconcat, we should know the type by now
     946       29690 :     if (OpTok == tgtok::XListConcat) {
     947         468 :       if (TypedInit *Arg0 = dyn_cast<TypedInit>(InitList[0]))
     948         468 :         Type = Arg0->getType();
     949             :       else {
     950           0 :         InitList[0]->print(errs());
     951           0 :         Error(OpLoc, "expected a list");
     952           0 :         return nullptr;
     953             :       }
     954             :     }
     955             : 
     956             :     // We allow multiple operands to associative operators like !strconcat as
     957             :     // shorthand for nesting them.
     958       29690 :     if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT) {
     959       29997 :       while (InitList.size() > 2) {
     960             :         Init *RHS = InitList.pop_back_val();
     961        8100 :         RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))
     962        4050 :                            ->Fold(CurRec, CurMultiClass);
     963        4050 :         InitList.back() = RHS;
     964             :       }
     965             :     }
     966             : 
     967       29690 :     if (InitList.size() == 2)
     968       29690 :       return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
     969       29690 :         ->Fold(CurRec, CurMultiClass);
     970             : 
     971           0 :     Error(OpLoc, "expected two operands to operator");
     972           0 :     return nullptr;
     973             :   }
     974             : 
     975       12501 :   case tgtok::XIf:
     976             :   case tgtok::XForEach:
     977             :   case tgtok::XSubst: {  // Value ::= !ternop '(' Value ',' Value ',' Value ')'
     978             :     TernOpInit::TernaryOp Code;
     979             :     RecTy *Type = nullptr;
     980             : 
     981             :     tgtok::TokKind LexCode = Lex.getCode();
     982       12501 :     Lex.Lex();  // eat the operation
     983       12501 :     switch (LexCode) {
     984           0 :     default: llvm_unreachable("Unhandled code!");
     985             :     case tgtok::XIf:
     986             :       Code = TernOpInit::IF;
     987             :       break;
     988          21 :     case tgtok::XForEach:
     989             :       Code = TernOpInit::FOREACH;
     990          21 :       break;
     991         165 :     case tgtok::XSubst:
     992             :       Code = TernOpInit::SUBST;
     993         165 :       break;
     994             :     }
     995       12501 :     if (Lex.getCode() != tgtok::l_paren) {
     996           0 :       TokError("expected '(' after ternary operator");
     997           0 :       return nullptr;
     998             :     }
     999             :     Lex.Lex();  // eat the '('
    1000             : 
    1001       12501 :     Init *LHS = ParseValue(CurRec);
    1002       12501 :     if (!LHS) return nullptr;
    1003             : 
    1004       12501 :     if (Lex.getCode() != tgtok::comma) {
    1005           0 :       TokError("expected ',' in ternary operator");
    1006           0 :       return nullptr;
    1007             :     }
    1008             :     Lex.Lex();  // eat the ','
    1009             : 
    1010       12501 :     Init *MHS = ParseValue(CurRec, ItemType);
    1011       12501 :     if (!MHS)
    1012             :       return nullptr;
    1013             : 
    1014       12501 :     if (Lex.getCode() != tgtok::comma) {
    1015           0 :       TokError("expected ',' in ternary operator");
    1016           0 :       return nullptr;
    1017             :     }
    1018             :     Lex.Lex();  // eat the ','
    1019             : 
    1020       12501 :     Init *RHS = ParseValue(CurRec, ItemType);
    1021       12501 :     if (!RHS)
    1022             :       return nullptr;
    1023             : 
    1024       12501 :     if (Lex.getCode() != tgtok::r_paren) {
    1025           0 :       TokError("expected ')' in binary operator");
    1026           0 :       return nullptr;
    1027             :     }
    1028             :     Lex.Lex();  // eat the ')'
    1029             : 
    1030       12501 :     switch (LexCode) {
    1031           0 :     default: llvm_unreachable("Unhandled code!");
    1032       12315 :     case tgtok::XIf: {
    1033             :       RecTy *MHSTy = nullptr;
    1034             :       RecTy *RHSTy = nullptr;
    1035             : 
    1036             :       if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
    1037       12250 :         MHSTy = MHSt->getType();
    1038             :       if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
    1039        1293 :         MHSTy = BitsRecTy::get(MHSbits->getNumBits());
    1040       12315 :       if (isa<BitInit>(MHS))
    1041             :         MHSTy = BitRecTy::get();
    1042             : 
    1043             :       if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
    1044       11428 :         RHSTy = RHSt->getType();
    1045             :       if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
    1046         131 :         RHSTy = BitsRecTy::get(RHSbits->getNumBits());
    1047       12315 :       if (isa<BitInit>(RHS))
    1048             :         RHSTy = BitRecTy::get();
    1049             : 
    1050             :       // For UnsetInit, it's typed from the other hand.
    1051       12315 :       if (isa<UnsetInit>(MHS))
    1052             :         MHSTy = RHSTy;
    1053       12315 :       if (isa<UnsetInit>(RHS))
    1054             :         RHSTy = MHSTy;
    1055             : 
    1056       12315 :       if (!MHSTy || !RHSTy) {
    1057           0 :         TokError("could not get type for !if");
    1058           0 :         return nullptr;
    1059             :       }
    1060             : 
    1061       12315 :       if (MHSTy->typeIsConvertibleTo(RHSTy)) {
    1062             :         Type = RHSTy;
    1063         314 :       } else if (RHSTy->typeIsConvertibleTo(MHSTy)) {
    1064             :         Type = MHSTy;
    1065             :       } else {
    1066           0 :         TokError("inconsistent types for !if");
    1067           0 :         return nullptr;
    1068             :       }
    1069             :       break;
    1070             :     }
    1071          21 :     case tgtok::XForEach: {
    1072             :       TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
    1073             :       if (!MHSt) {
    1074           0 :         TokError("could not get type for !foreach");
    1075           0 :         return nullptr;
    1076             :       }
    1077          21 :       Type = MHSt->getType();
    1078          21 :       if (isa<ListRecTy>(Type)) {
    1079             :         TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
    1080             :         if (!RHSt) {
    1081           0 :           TokError("could not get type of !foreach list elements");
    1082           0 :           return nullptr;
    1083             :         }
    1084          13 :         Type = RHSt->getType()->getListTy();
    1085             :       }
    1086             :       break;
    1087             :     }
    1088         165 :     case tgtok::XSubst: {
    1089             :       TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
    1090             :       if (!RHSt) {
    1091           0 :         TokError("could not get type for !subst");
    1092           0 :         return nullptr;
    1093             :       }
    1094         165 :       Type = RHSt->getType();
    1095         165 :       break;
    1096             :     }
    1097             :     }
    1098       25002 :     return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
    1099       25002 :                                                              CurMultiClass);
    1100             :   }
    1101             :   }
    1102             : }
    1103             : 
    1104             : /// ParseOperatorType - Parse a type for an operator.  This returns
    1105             : /// null on error.
    1106             : ///
    1107             : /// OperatorType ::= '<' Type '>'
    1108             : ///
    1109       20249 : RecTy *TGParser::ParseOperatorType() {
    1110             :   RecTy *Type = nullptr;
    1111             : 
    1112       20249 :   if (Lex.getCode() != tgtok::less) {
    1113           0 :     TokError("expected type name for operator");
    1114           0 :     return nullptr;
    1115             :   }
    1116       20249 :   Lex.Lex();  // eat the <
    1117             : 
    1118       20249 :   Type = ParseType();
    1119             : 
    1120       20249 :   if (!Type) {
    1121           0 :     TokError("expected type name for operator");
    1122           0 :     return nullptr;
    1123             :   }
    1124             : 
    1125       20249 :   if (Lex.getCode() != tgtok::greater) {
    1126           0 :     TokError("expected type name for operator");
    1127           0 :     return nullptr;
    1128             :   }
    1129             :   Lex.Lex();  // eat the >
    1130             : 
    1131       20249 :   return Type;
    1132             : }
    1133             : 
    1134             : /// ParseSimpleValue - Parse a tblgen value.  This returns null on error.
    1135             : ///
    1136             : ///   SimpleValue ::= IDValue
    1137             : ///   SimpleValue ::= INTVAL
    1138             : ///   SimpleValue ::= STRVAL+
    1139             : ///   SimpleValue ::= CODEFRAGMENT
    1140             : ///   SimpleValue ::= '?'
    1141             : ///   SimpleValue ::= '{' ValueList '}'
    1142             : ///   SimpleValue ::= ID '<' ValueListNE '>'
    1143             : ///   SimpleValue ::= '[' ValueList ']'
    1144             : ///   SimpleValue ::= '(' IDValue DagArgList ')'
    1145             : ///   SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
    1146             : ///   SimpleValue ::= ADDTOK '(' Value ',' Value ')'
    1147             : ///   SimpleValue ::= SHLTOK '(' Value ',' Value ')'
    1148             : ///   SimpleValue ::= SRATOK '(' Value ',' Value ')'
    1149             : ///   SimpleValue ::= SRLTOK '(' Value ',' Value ')'
    1150             : ///   SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
    1151             : ///   SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
    1152             : ///
    1153    16584244 : Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
    1154             :                                  IDParseMode Mode) {
    1155             :   Init *R = nullptr;
    1156    16584244 :   switch (Lex.getCode()) {
    1157           0 :   default: TokError("Unknown token when parsing a value"); break;
    1158       15772 :   case tgtok::paste:
    1159             :     // This is a leading paste operation.  This is deprecated but
    1160             :     // still exists in some .td files.  Ignore it.
    1161       15772 :     Lex.Lex();  // Skip '#'.
    1162       15772 :     return ParseSimpleValue(CurRec, ItemType, Mode);
    1163     1103487 :   case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
    1164      218464 :   case tgtok::BinaryIntVal: {
    1165             :     auto BinaryVal = Lex.getCurBinaryIntVal();
    1166      436928 :     SmallVector<Init*, 16> Bits(BinaryVal.second);
    1167     2065774 :     for (unsigned i = 0, e = BinaryVal.second; i != e; ++i)
    1168     1847310 :       Bits[i] = BitInit::get(BinaryVal.first & (1LL << i));
    1169      218464 :     R = BitsInit::get(Bits);
    1170      218464 :     Lex.Lex();
    1171             :     break;
    1172             :   }
    1173     1861583 :   case tgtok::StrVal: {
    1174             :     std::string Val = Lex.getCurStrVal();
    1175     1861583 :     Lex.Lex();
    1176             : 
    1177             :     // Handle multiple consecutive concatenated strings.
    1178     1893717 :     while (Lex.getCode() == tgtok::StrVal) {
    1179             :       Val += Lex.getCurStrVal();
    1180             :       Lex.Lex();
    1181             :     }
    1182             : 
    1183     1861583 :     R = StringInit::get(Val);
    1184             :     break;
    1185             :   }
    1186       17068 :   case tgtok::CodeFragment:
    1187       17068 :     R = CodeInit::get(Lex.getCurStrVal());
    1188       17068 :     Lex.Lex();
    1189             :     break;
    1190       21148 :   case tgtok::question:
    1191       21148 :     R = UnsetInit::get();
    1192       21148 :     Lex.Lex();
    1193             :     break;
    1194     9375261 :   case tgtok::Id: {
    1195     9375261 :     SMLoc NameLoc = Lex.getLoc();
    1196     9375261 :     StringInit *Name = StringInit::get(Lex.getCurStrVal());
    1197     9375261 :     if (Lex.Lex() != tgtok::less)  // consume the Id.
    1198     9100616 :       return ParseIDValue(CurRec, Name, NameLoc, Mode);    // Value ::= IDValue
    1199             : 
    1200             :     // Value ::= ID '<' ValueListNE '>'
    1201      274645 :     if (Lex.Lex() == tgtok::greater) {
    1202           0 :       TokError("expected non-empty value list");
    1203           0 :       return nullptr;
    1204             :     }
    1205             : 
    1206             :     // This is a CLASS<initvalslist> expression.  This is supposed to synthesize
    1207             :     // a new anonymous definition, deriving from CLASS<initvalslist> with no
    1208             :     // body.
    1209      274645 :     Record *Class = Records.getClass(Name->getValue());
    1210      274645 :     if (!Class) {
    1211           0 :       Error(NameLoc, "Expected a class name, got '" + Name->getValue() + "'");
    1212           0 :       return nullptr;
    1213             :     }
    1214             : 
    1215             :     SubClassReference SCRef;
    1216      274645 :     ParseValueList(SCRef.TemplateArgs, CurRec, Class);
    1217      274645 :     if (SCRef.TemplateArgs.empty()) return nullptr;
    1218             : 
    1219      274645 :     if (Lex.getCode() != tgtok::greater) {
    1220           0 :       TokError("expected '>' at end of value list");
    1221           0 :       return nullptr;
    1222             :     }
    1223             :     Lex.Lex();  // eat the '>'
    1224      274645 :     SMLoc EndLoc = Lex.getLoc();
    1225             : 
    1226             :     // Create the new record, set it as CurRec temporarily.
    1227      274645 :     auto NewRecOwner = llvm::make_unique<Record>(GetNewAnonymousName(), NameLoc,
    1228      823935 :                                                  Records, /*IsAnonymous=*/true);
    1229             :     Record *NewRec = NewRecOwner.get(); // Keep a copy since we may release.
    1230      274645 :     SCRef.RefRange = SMRange(NameLoc, EndLoc);
    1231      274645 :     SCRef.Rec = Class;
    1232             :     // Add info about the subclass to NewRec.
    1233      274645 :     if (AddSubClass(NewRec, SCRef))
    1234             :       return nullptr;
    1235             : 
    1236      274645 :     if (!CurMultiClass) {
    1237             :       NewRec->resolveReferences();
    1238      545808 :       Records.addDef(std::move(NewRecOwner));
    1239             :     } else {
    1240             :       // This needs to get resolved once the multiclass template arguments are
    1241             :       // known before any use.
    1242             :       NewRec->setResolveFirst(true);
    1243             :       // Otherwise, we're inside a multiclass, add it to the multiclass.
    1244        1741 :       CurMultiClass->DefPrototypes.push_back(std::move(NewRecOwner));
    1245             : 
    1246             :       // Copy the template arguments for the multiclass into the def.
    1247       10902 :       for (Init *TArg : CurMultiClass->Rec.getTemplateArgs()) {
    1248        3710 :         const RecordVal *RV = CurMultiClass->Rec.getValue(TArg);
    1249             :         assert(RV && "Template arg doesn't exist?");
    1250        3710 :         NewRec->addValue(*RV);
    1251             :       }
    1252             : 
    1253             :       // We can't return the prototype def here, instead return:
    1254             :       // !cast<ItemType>(!strconcat(NAME, AnonName)).
    1255        3482 :       const RecordVal *MCNameRV = CurMultiClass->Rec.getValue("NAME");
    1256             :       assert(MCNameRV && "multiclass record must have a NAME");
    1257             : 
    1258        1741 :       return UnOpInit::get(UnOpInit::CAST,
    1259        3482 :                            BinOpInit::get(BinOpInit::STRCONCAT,
    1260        1741 :                                           VarInit::get(MCNameRV->getName(),
    1261             :                                                        MCNameRV->getType()),
    1262             :                                           NewRec->getNameInit(),
    1263             :                                           StringRecTy::get()),
    1264        3482 :                            Class->getDefInit()->getType());
    1265             :     }
    1266             : 
    1267             :     // The result of the expression is a reference to the new record.
    1268      272904 :     return DefInit::get(NewRec);
    1269             :   }
    1270        7993 :   case tgtok::l_brace: {           // Value ::= '{' ValueList '}'
    1271        7993 :     SMLoc BraceLoc = Lex.getLoc();
    1272             :     Lex.Lex(); // eat the '{'
    1273             :     SmallVector<Init*, 16> Vals;
    1274             : 
    1275        7993 :     if (Lex.getCode() != tgtok::r_brace) {
    1276        7993 :       ParseValueList(Vals, CurRec);
    1277        7993 :       if (Vals.empty()) return nullptr;
    1278             :     }
    1279        7993 :     if (Lex.getCode() != tgtok::r_brace) {
    1280           0 :       TokError("expected '}' at end of bit list value");
    1281           0 :       return nullptr;
    1282             :     }
    1283             :     Lex.Lex();  // eat the '}'
    1284             : 
    1285             :     SmallVector<Init *, 16> NewBits;
    1286             : 
    1287             :     // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it
    1288             :     // first.  We'll first read everything in to a vector, then we can reverse
    1289             :     // it to get the bits in the correct order for the BitsInit value.
    1290       41688 :     for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
    1291             :       // FIXME: The following two loops would not be duplicated
    1292             :       //        if the API was a little more orthogonal.
    1293             : 
    1294             :       // bits<n> values are allowed to initialize n bits.
    1295       67392 :       if (BitsInit *BI = dyn_cast<BitsInit>(Vals[i])) {
    1296        4967 :         for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
    1297        6196 :           NewBits.push_back(BI->getBit((e - i) - 1));
    1298        4133 :         continue;
    1299             :       }
    1300             :       // bits<n> can also come from variable initializers.
    1301             :       if (VarInit *VI = dyn_cast<VarInit>(Vals[i])) {
    1302        1500 :         if (BitsRecTy *BitsRec = dyn_cast<BitsRecTy>(VI->getType())) {
    1303        1511 :           for (unsigned i = 0, e = BitsRec->getNumBits(); i != e; ++i)
    1304        1116 :             NewBits.push_back(VI->getBit((e - i) - 1));
    1305         395 :           continue;
    1306             :         }
    1307             :         // Fallthrough to try convert this to a bit.
    1308             :       }
    1309             :       // All other values must be convertible to just a single bit.
    1310       31432 :       Init *Bit = Vals[i]->convertInitializerTo(BitRecTy::get());
    1311       31432 :       if (!Bit) {
    1312           3 :         Error(BraceLoc, "Element #" + Twine(i) + " (" + Vals[i]->getAsString() +
    1313           1 :               ") is not convertable to a bit");
    1314           1 :         return nullptr;
    1315             :       }
    1316       31431 :       NewBits.push_back(Bit);
    1317             :     }
    1318             :     std::reverse(NewBits.begin(), NewBits.end());
    1319        7992 :     return BitsInit::get(NewBits);
    1320             :   }
    1321     2751064 :   case tgtok::l_square: {          // Value ::= '[' ValueList ']'
    1322     2751064 :     Lex.Lex(); // eat the '['
    1323             :     SmallVector<Init*, 16> Vals;
    1324             : 
    1325             :     RecTy *DeducedEltTy = nullptr;
    1326             :     ListRecTy *GivenListTy = nullptr;
    1327             : 
    1328     2751064 :     if (ItemType) {
    1329             :       ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
    1330             :       if (!ListType) {
    1331           0 :         TokError(Twine("Type mismatch for list, expected list type, got ") +
    1332           0 :                  ItemType->getAsString());
    1333           0 :         return nullptr;
    1334             :       }
    1335             :       GivenListTy = ListType;
    1336             :     }
    1337             : 
    1338     2751064 :     if (Lex.getCode() != tgtok::r_square) {
    1339     2443516 :       ParseValueList(Vals, CurRec, nullptr,
    1340             :                      GivenListTy ? GivenListTy->getElementType() : nullptr);
    1341     2443516 :       if (Vals.empty()) return nullptr;
    1342             :     }
    1343     2751064 :     if (Lex.getCode() != tgtok::r_square) {
    1344           0 :       TokError("expected ']' at end of list value");
    1345           0 :       return nullptr;
    1346             :     }
    1347             :     Lex.Lex();  // eat the ']'
    1348             : 
    1349             :     RecTy *GivenEltTy = nullptr;
    1350     2751064 :     if (Lex.getCode() == tgtok::less) {
    1351             :       // Optional list element type
    1352             :       Lex.Lex();  // eat the '<'
    1353             : 
    1354         104 :       GivenEltTy = ParseType();
    1355         104 :       if (!GivenEltTy) {
    1356             :         // Couldn't parse element type
    1357             :         return nullptr;
    1358             :       }
    1359             : 
    1360         104 :       if (Lex.getCode() != tgtok::greater) {
    1361           0 :         TokError("expected '>' at end of list element type");
    1362           0 :         return nullptr;
    1363             :       }
    1364             :       Lex.Lex();  // eat the '>'
    1365             :     }
    1366             : 
    1367             :     // Check elements
    1368             :     RecTy *EltTy = nullptr;
    1369    11400808 :     for (Init *V : Vals) {
    1370             :       TypedInit *TArg = dyn_cast<TypedInit>(V);
    1371             :       if (!TArg) {
    1372           0 :         TokError("Untyped list element");
    1373           0 :         return nullptr;
    1374             :       }
    1375     4324872 :       if (EltTy) {
    1376     1881356 :         EltTy = resolveTypes(EltTy, TArg->getType());
    1377     1881356 :         if (!EltTy) {
    1378           0 :           TokError("Incompatible types in list elements");
    1379           0 :           return nullptr;
    1380             :         }
    1381             :       } else {
    1382     2443516 :         EltTy = TArg->getType();
    1383             :       }
    1384             :     }
    1385             : 
    1386     2751064 :     if (GivenEltTy) {
    1387         104 :       if (EltTy) {
    1388             :         // Verify consistency
    1389           0 :         if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
    1390           0 :           TokError("Incompatible types in list elements");
    1391           0 :           return nullptr;
    1392             :         }
    1393             :       }
    1394             :       EltTy = GivenEltTy;
    1395             :     }
    1396             : 
    1397     2751064 :     if (!EltTy) {
    1398      307444 :       if (!ItemType) {
    1399           0 :         TokError("No type for list");
    1400           0 :         return nullptr;
    1401             :       }
    1402      307444 :       DeducedEltTy = GivenListTy->getElementType();
    1403             :     } else {
    1404             :       // Make sure the deduced type is compatible with the given type
    1405     2443620 :       if (GivenListTy) {
    1406     2408488 :         if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
    1407           0 :           TokError(Twine("Element type mismatch for list: element type '") +
    1408           0 :                    EltTy->getAsString() + "' not convertible to '" +
    1409           0 :                    GivenListTy->getElementType()->getAsString());
    1410           0 :           return nullptr;
    1411             :         }
    1412             :       }
    1413             :       DeducedEltTy = EltTy;
    1414             :     }
    1415             : 
    1416     2751064 :     return ListInit::get(Vals, DeducedEltTy);
    1417             :   }
    1418     1149704 :   case tgtok::l_paren: {         // Value ::= '(' IDValue DagArgList ')'
    1419     1149704 :     Lex.Lex();   // eat the '('
    1420     1149704 :     if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
    1421           0 :       TokError("expected identifier in dag init");
    1422           0 :       return nullptr;
    1423             :     }
    1424             : 
    1425     1149704 :     Init *Operator = ParseValue(CurRec);
    1426     1149704 :     if (!Operator) return nullptr;
    1427             : 
    1428             :     // If the operator name is present, parse it.
    1429             :     StringInit *OperatorName = nullptr;
    1430     1149704 :     if (Lex.getCode() == tgtok::colon) {
    1431        1281 :       if (Lex.Lex() != tgtok::VarName) { // eat the ':'
    1432           0 :         TokError("expected variable name in dag operator");
    1433           0 :         return nullptr;
    1434             :       }
    1435        1281 :       OperatorName = StringInit::get(Lex.getCurStrVal());
    1436             :       Lex.Lex();  // eat the VarName.
    1437             :     }
    1438             : 
    1439             :     SmallVector<std::pair<llvm::Init*, StringInit*>, 8> DagArgs;
    1440     1149704 :     if (Lex.getCode() != tgtok::r_paren) {
    1441     1089668 :       ParseDagArgList(DagArgs, CurRec);
    1442     1089668 :       if (DagArgs.empty()) return nullptr;
    1443             :     }
    1444             : 
    1445     1149704 :     if (Lex.getCode() != tgtok::r_paren) {
    1446           0 :       TokError("expected ')' in dag init");
    1447           0 :       return nullptr;
    1448             :     }
    1449             :     Lex.Lex();  // eat the ')'
    1450             : 
    1451     1149704 :     return DagInit::get(Operator, OperatorName, DagArgs);
    1452             :   }
    1453             : 
    1454       62700 :   case tgtok::XHead:
    1455             :   case tgtok::XTail:
    1456             :   case tgtok::XEmpty:
    1457             :   case tgtok::XCast:  // Value ::= !unop '(' Value ')'
    1458             :   case tgtok::XConcat:
    1459             :   case tgtok::XADD:
    1460             :   case tgtok::XAND:
    1461             :   case tgtok::XOR:
    1462             :   case tgtok::XSRA:
    1463             :   case tgtok::XSRL:
    1464             :   case tgtok::XSHL:
    1465             :   case tgtok::XEq:
    1466             :   case tgtok::XListConcat:
    1467             :   case tgtok::XStrConcat:   // Value ::= !binop '(' Value ',' Value ')'
    1468             :   case tgtok::XIf:
    1469             :   case tgtok::XForEach:
    1470             :   case tgtok::XSubst: {  // Value ::= !ternop '(' Value ',' Value ',' Value ')'
    1471       62700 :     return ParseOperation(CurRec, ItemType);
    1472             :   }
    1473             :   }
    1474             : 
    1475             :   return R;
    1476             : }
    1477             : 
    1478             : /// ParseValue - Parse a tblgen value.  This returns null on error.
    1479             : ///
    1480             : ///   Value       ::= SimpleValue ValueSuffix*
    1481             : ///   ValueSuffix ::= '{' BitList '}'
    1482             : ///   ValueSuffix ::= '[' BitList ']'
    1483             : ///   ValueSuffix ::= '.' ID
    1484             : ///
    1485    16568230 : Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
    1486    16568230 :   Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
    1487    16568230 :   if (!Result) return nullptr;
    1488             : 
    1489             :   // Parse the suffixes now if present.
    1490             :   while (true) {
    1491    16773029 :     switch (Lex.getCode()) {
    1492    16568229 :     default: return Result;
    1493       43412 :     case tgtok::l_brace: {
    1494       43412 :       if (Mode == ParseNameMode || Mode == ParseForeachMode)
    1495             :         // This is the beginning of the object body.
    1496         676 :         return Result;
    1497             : 
    1498       42736 :       SMLoc CurlyLoc = Lex.getLoc();
    1499             :       Lex.Lex(); // eat the '{'
    1500             :       SmallVector<unsigned, 16> Ranges;
    1501       42736 :       ParseRangeList(Ranges);
    1502       42736 :       if (Ranges.empty()) return nullptr;
    1503             : 
    1504             :       // Reverse the bitlist.
    1505             :       std::reverse(Ranges.begin(), Ranges.end());
    1506       85472 :       Result = Result->convertInitializerBitRange(Ranges);
    1507       42736 :       if (!Result) {
    1508           0 :         Error(CurlyLoc, "Invalid bit range for value");
    1509           0 :         return nullptr;
    1510             :       }
    1511             : 
    1512             :       // Eat the '}'.
    1513       42736 :       if (Lex.getCode() != tgtok::r_brace) {
    1514           0 :         TokError("expected '}' at end of bit range list");
    1515           0 :         return nullptr;
    1516             :       }
    1517             :       Lex.Lex();
    1518             :       break;
    1519             :     }
    1520        1215 :     case tgtok::l_square: {
    1521        1215 :       SMLoc SquareLoc = Lex.getLoc();
    1522             :       Lex.Lex(); // eat the '['
    1523             :       SmallVector<unsigned, 16> Ranges;
    1524        1215 :       ParseRangeList(Ranges);
    1525        1215 :       if (Ranges.empty()) return nullptr;
    1526             : 
    1527        2430 :       Result = Result->convertInitListSlice(Ranges);
    1528        1215 :       if (!Result) {
    1529           0 :         Error(SquareLoc, "Invalid range for list slice");
    1530           0 :         return nullptr;
    1531             :       }
    1532             : 
    1533             :       // Eat the ']'.
    1534        1215 :       if (Lex.getCode() != tgtok::r_square) {
    1535           0 :         TokError("expected ']' at end of list slice");
    1536           0 :         return nullptr;
    1537             :       }
    1538             :       Lex.Lex();
    1539             :       break;
    1540             :     }
    1541       87244 :     case tgtok::period: {
    1542      174488 :       if (Lex.Lex() != tgtok::Id) {  // eat the .
    1543           0 :         TokError("expected field identifier after '.'");
    1544           0 :         return nullptr;
    1545             :       }
    1546       87244 :       StringInit *FieldName = StringInit::get(Lex.getCurStrVal());
    1547       87244 :       if (!Result->getFieldType(FieldName)) {
    1548           0 :         TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
    1549           0 :                  Result->getAsString() + "'");
    1550           0 :         return nullptr;
    1551             :       }
    1552       87244 :       Result = FieldInit::get(Result, FieldName);
    1553             :       Lex.Lex();  // eat field name
    1554             :       break;
    1555             :     }
    1556             : 
    1557       73605 :     case tgtok::paste:
    1558       73605 :       SMLoc PasteLoc = Lex.getLoc();
    1559             : 
    1560             :       // Create a !strconcat() operation, first casting each operand to
    1561             :       // a string if necessary.
    1562             : 
    1563             :       TypedInit *LHS = dyn_cast<TypedInit>(Result);
    1564             :       if (!LHS) {
    1565           0 :         Error(PasteLoc, "LHS of paste is not typed!");
    1566           0 :         return nullptr;
    1567             :       }
    1568             : 
    1569       73605 :       if (LHS->getType() != StringRecTy::get()) {
    1570        4221 :         LHS = UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get());
    1571             :       }
    1572             : 
    1573             :       TypedInit *RHS = nullptr;
    1574             : 
    1575             :       Lex.Lex();  // Eat the '#'.
    1576             :       switch (Lex.getCode()) { 
    1577             :       case tgtok::colon:
    1578             :       case tgtok::semi:
    1579             :       case tgtok::l_brace:
    1580             :         // These are all of the tokens that can begin an object body.
    1581             :         // Some of these can also begin values but we disallow those cases
    1582             :         // because they are unlikely to be useful.
    1583             : 
    1584             :         // Trailing paste, concat with an empty string.
    1585          20 :         RHS = StringInit::get("");
    1586          20 :         break;
    1587             : 
    1588       73585 :       default:
    1589       73585 :         Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode);
    1590             :         RHS = dyn_cast<TypedInit>(RHSResult);
    1591             :         if (!RHS) {
    1592           0 :           Error(PasteLoc, "RHS of paste is not typed!");
    1593           0 :           return nullptr;
    1594             :         }
    1595             : 
    1596       73585 :         if (RHS->getType() != StringRecTy::get()) {
    1597        3914 :           RHS = UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get());
    1598             :         }
    1599             : 
    1600             :         break;
    1601             :       }
    1602             : 
    1603      147210 :       Result = BinOpInit::get(BinOpInit::STRCONCAT, LHS, RHS,
    1604       73605 :                               StringRecTy::get())->Fold(CurRec, CurMultiClass);
    1605       73605 :       break;
    1606             :     }
    1607      204800 :   }
    1608             : }
    1609             : 
    1610             : /// ParseDagArgList - Parse the argument list for a dag literal expression.
    1611             : ///
    1612             : ///    DagArg     ::= Value (':' VARNAME)?
    1613             : ///    DagArg     ::= VARNAME
    1614             : ///    DagArgList ::= DagArg
    1615             : ///    DagArgList ::= DagArgList ',' DagArg
    1616     1089668 : void TGParser::ParseDagArgList(
    1617             :     SmallVectorImpl<std::pair<llvm::Init*, StringInit*>> &Result,
    1618             :     Record *CurRec) {
    1619             : 
    1620             :   while (true) {
    1621             :     // DagArg ::= VARNAME
    1622     1728448 :     if (Lex.getCode() == tgtok::VarName) {
    1623             :       // A missing value is treated like '?'.
    1624       33553 :       StringInit *VarName = StringInit::get(Lex.getCurStrVal());
    1625       33553 :       Result.emplace_back(UnsetInit::get(), VarName);
    1626       33553 :       Lex.Lex();
    1627             :     } else {
    1628             :       // DagArg ::= Value (':' VARNAME)?
    1629     1694895 :       Init *Val = ParseValue(CurRec);
    1630     1694895 :       if (!Val) {
    1631             :         Result.clear();
    1632             :         return;
    1633             :       }
    1634             : 
    1635             :       // If the variable name is present, add it.
    1636             :       StringInit *VarName = nullptr;
    1637     1694895 :       if (Lex.getCode() == tgtok::colon) {
    1638     1879174 :         if (Lex.Lex() != tgtok::VarName) { // eat the ':'
    1639           0 :           TokError("expected variable name in dag literal");
    1640             :           Result.clear();
    1641             :           return;
    1642             :         }
    1643      939587 :         VarName = StringInit::get(Lex.getCurStrVal());
    1644             :         Lex.Lex();  // eat the VarName.
    1645             :       }
    1646             : 
    1647     1694895 :       Result.push_back(std::make_pair(Val, VarName));
    1648             :     }
    1649     1728448 :     if (Lex.getCode() != tgtok::comma) break;
    1650      638780 :     Lex.Lex(); // eat the ','
    1651             :   }
    1652             : }
    1653             : 
    1654             : /// ParseValueList - Parse a comma separated list of values, returning them as a
    1655             : /// vector.  Note that this always expects to be able to parse at least one
    1656             : /// value.  It returns an empty list if this is not possible.
    1657             : ///
    1658             : ///   ValueList ::= Value (',' Value)
    1659             : ///
    1660     5381331 : void TGParser::ParseValueList(SmallVectorImpl<Init*> &Result, Record *CurRec,
    1661             :                               Record *ArgsRec, RecTy *EltTy) {
    1662             :   RecTy *ItemType = EltTy;
    1663             :   unsigned int ArgN = 0;
    1664     5381331 :   if (ArgsRec && !EltTy) {
    1665             :     ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs();
    1666     2929822 :     if (TArgs.empty()) {
    1667           0 :       TokError("template argument provided to non-template class");
    1668             :       Result.clear();
    1669             :       return;
    1670             :     }
    1671     2929822 :     const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
    1672     2929822 :     if (!RV) {
    1673           0 :       errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
    1674           0 :         << ")\n";
    1675             :     }
    1676             :     assert(RV && "Template argument record not found??");
    1677             :     ItemType = RV->getType();
    1678             :     ++ArgN;
    1679             :   }
    1680     5381331 :   Result.push_back(ParseValue(CurRec, ItemType));
    1681     5381331 :   if (!Result.back()) {
    1682             :     Result.clear();
    1683             :     return;
    1684             :   }
    1685             : 
    1686    11029368 :   while (Lex.getCode() == tgtok::comma) {
    1687     5648037 :     Lex.Lex();  // Eat the comma
    1688             : 
    1689     5648037 :     if (ArgsRec && !EltTy) {
    1690             :       ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs();
    1691     3740978 :       if (ArgN >= TArgs.size()) {
    1692           0 :         TokError("too many template arguments");
    1693             :         Result.clear();
    1694             :         return;
    1695             :       }
    1696     3740978 :       const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
    1697             :       assert(RV && "Template argument record not found??");
    1698             :       ItemType = RV->getType();
    1699     3740978 :       ++ArgN;
    1700             :     }
    1701     5648037 :     Result.push_back(ParseValue(CurRec, ItemType));
    1702     5648037 :     if (!Result.back()) {
    1703             :       Result.clear();
    1704             :       return;
    1705             :     }
    1706             :   }
    1707             : }
    1708             : 
    1709             : /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
    1710             : /// empty string on error.  This can happen in a number of different context's,
    1711             : /// including within a def or in the template args for a def (which which case
    1712             : /// CurRec will be non-null) and within the template args for a multiclass (in
    1713             : /// which case CurRec will be null, but CurMultiClass will be set).  This can
    1714             : /// also happen within a def that is within a multiclass, which will set both
    1715             : /// CurRec and CurMultiClass.
    1716             : ///
    1717             : ///  Declaration ::= FIELD? Type ID ('=' Value)?
    1718             : ///
    1719      489738 : Init *TGParser::ParseDeclaration(Record *CurRec,
    1720             :                                        bool ParsingTemplateArgs) {
    1721             :   // Read the field prefix if present.
    1722      489738 :   bool HasField = Lex.getCode() == tgtok::Field;
    1723      489738 :   if (HasField) Lex.Lex();
    1724             : 
    1725      489738 :   RecTy *Type = ParseType();
    1726      489738 :   if (!Type) return nullptr;
    1727             : 
    1728      489738 :   if (Lex.getCode() != tgtok::Id) {
    1729           0 :     TokError("Expected identifier in declaration");
    1730           0 :     return nullptr;
    1731             :   }
    1732             : 
    1733      489738 :   SMLoc IdLoc = Lex.getLoc();
    1734      489738 :   Init *DeclName = StringInit::get(Lex.getCurStrVal());
    1735             :   Lex.Lex();
    1736             : 
    1737      489738 :   if (ParsingTemplateArgs) {
    1738      338557 :     if (CurRec)
    1739      249287 :       DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
    1740             :     else
    1741             :       assert(CurMultiClass);
    1742      338557 :     if (CurMultiClass)
    1743       89270 :       DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
    1744             :                              "::");
    1745             :   }
    1746             : 
    1747             :   // Add the value.
    1748      489738 :   if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
    1749             :     return nullptr;
    1750             : 
    1751             :   // If a value is present, parse it.
    1752      489738 :   if (Lex.getCode() == tgtok::equal) {
    1753             :     Lex.Lex();
    1754      110511 :     SMLoc ValLoc = Lex.getLoc();
    1755      110511 :     Init *Val = ParseValue(CurRec, Type);
    1756      221021 :     if (!Val ||
    1757      221021 :         SetValue(CurRec, ValLoc, DeclName, None, Val))
    1758             :       // Return the name, even if an error is thrown.  This is so that we can
    1759             :       // continue to make some progress, even without the value having been
    1760             :       // initialized.
    1761          10 :       return DeclName;
    1762             :   }
    1763             : 
    1764             :   return DeclName;
    1765             : }
    1766             : 
    1767             : /// ParseForeachDeclaration - Read a foreach declaration, returning
    1768             : /// the name of the declared object or a NULL Init on error.  Return
    1769             : /// the name of the parsed initializer list through ForeachListName.
    1770             : ///
    1771             : ///  ForeachDeclaration ::= ID '=' '[' ValueList ']'
    1772             : ///  ForeachDeclaration ::= ID '=' '{' RangeList '}'
    1773             : ///  ForeachDeclaration ::= ID '=' RangePiece
    1774             : ///
    1775        1298 : VarInit *TGParser::ParseForeachDeclaration(ListInit *&ForeachListValue) {
    1776        1298 :   if (Lex.getCode() != tgtok::Id) {
    1777           0 :     TokError("Expected identifier in foreach declaration");
    1778           0 :     return nullptr;
    1779             :   }
    1780             : 
    1781        1298 :   Init *DeclName = StringInit::get(Lex.getCurStrVal());
    1782        1298 :   Lex.Lex();
    1783             : 
    1784             :   // If a value is present, parse it.
    1785        1298 :   if (Lex.getCode() != tgtok::equal) {
    1786           0 :     TokError("Expected '=' in foreach declaration");
    1787           0 :     return nullptr;
    1788             :   }
    1789             :   Lex.Lex();  // Eat the '='
    1790             : 
    1791             :   RecTy *IterType = nullptr;
    1792             :   SmallVector<unsigned, 16> Ranges;
    1793             : 
    1794        1298 :   switch (Lex.getCode()) {
    1795           0 :   default: TokError("Unknown token when expecting a range list"); return nullptr;
    1796         242 :   case tgtok::l_square: { // '[' ValueList ']'
    1797         242 :     Init *List = ParseSimpleValue(nullptr, nullptr, ParseForeachMode);
    1798         242 :     ForeachListValue = dyn_cast<ListInit>(List);
    1799         242 :     if (!ForeachListValue) {
    1800           0 :       TokError("Expected a Value list");
    1801           0 :       return nullptr;
    1802             :     }
    1803         242 :     RecTy *ValueType = ForeachListValue->getType();
    1804             :     ListRecTy *ListType = dyn_cast<ListRecTy>(ValueType);
    1805             :     if (!ListType) {
    1806           0 :       TokError("Value list is not of list type");
    1807           0 :       return nullptr;
    1808             :     }
    1809         242 :     IterType = ListType->getElementType();
    1810         242 :     break;
    1811             :   }
    1812             : 
    1813         873 :   case tgtok::IntVal: { // RangePiece.
    1814         873 :     if (ParseRangePiece(Ranges))
    1815             :       return nullptr;
    1816             :     break;
    1817             :   }
    1818             : 
    1819         183 :   case tgtok::l_brace: { // '{' RangeList '}'
    1820             :     Lex.Lex(); // eat the '{'
    1821         183 :     ParseRangeList(Ranges);
    1822         183 :     if (Lex.getCode() != tgtok::r_brace) {
    1823           0 :       TokError("expected '}' at end of bit range list");
    1824           0 :       return nullptr;
    1825             :     }
    1826             :     Lex.Lex();
    1827             :     break;
    1828             :   }
    1829             :   }
    1830             : 
    1831        1298 :   if (!Ranges.empty()) {
    1832             :     assert(!IterType && "Type already initialized?");
    1833             :     IterType = IntRecTy::get();
    1834             :     std::vector<Init*> Values;
    1835       47780 :     for (unsigned R : Ranges)
    1836       46724 :       Values.push_back(IntInit::get(R));
    1837        1056 :     ForeachListValue = ListInit::get(Values, IterType);
    1838             :   }
    1839             : 
    1840        1298 :   if (!IterType)
    1841             :     return nullptr;
    1842             : 
    1843        1298 :   return VarInit::get(DeclName, IterType);
    1844             : }
    1845             : 
    1846             : /// ParseTemplateArgList - Read a template argument list, which is a non-empty
    1847             : /// sequence of template-declarations in <>'s.  If CurRec is non-null, these are
    1848             : /// template args for a def, which may or may not be in a multiclass.  If null,
    1849             : /// these are the template args for a multiclass.
    1850             : ///
    1851             : ///    TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
    1852             : ///
    1853      127884 : bool TGParser::ParseTemplateArgList(Record *CurRec) {
    1854             :   assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
    1855      127884 :   Lex.Lex(); // eat the '<'
    1856             : 
    1857      127884 :   Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
    1858             : 
    1859             :   // Read the first declaration.
    1860      127884 :   Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
    1861      127884 :   if (!TemplArg)
    1862             :     return true;
    1863             : 
    1864             :   TheRecToAddTo->addTemplateArg(TemplArg);
    1865             : 
    1866      338557 :   while (Lex.getCode() == tgtok::comma) {
    1867             :     Lex.Lex(); // eat the ','
    1868             : 
    1869             :     // Read the following declarations.
    1870      210673 :     TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
    1871      210673 :     if (!TemplArg)
    1872             :       return true;
    1873             :     TheRecToAddTo->addTemplateArg(TemplArg);
    1874             :   }
    1875             : 
    1876      127884 :   if (Lex.getCode() != tgtok::greater)
    1877           0 :     return TokError("expected '>' at end of template argument list");
    1878             :   Lex.Lex(); // eat the '>'.
    1879      127884 :   return false;
    1880             : }
    1881             : 
    1882             : /// ParseBodyItem - Parse a single item at within the body of a def or class.
    1883             : ///
    1884             : ///   BodyItem ::= Declaration ';'
    1885             : ///   BodyItem ::= LET ID OptionalBitList '=' Value ';'
    1886      786594 : bool TGParser::ParseBodyItem(Record *CurRec) {
    1887      786594 :   if (Lex.getCode() != tgtok::Let) {
    1888      151181 :     if (!ParseDeclaration(CurRec, false))
    1889             :       return true;
    1890             : 
    1891      151181 :     if (Lex.getCode() != tgtok::semi)
    1892           0 :       return TokError("expected ';' after declaration");
    1893      151181 :     Lex.Lex();
    1894      151181 :     return false;
    1895             :   }
    1896             : 
    1897             :   // LET ID OptionalRangeList '=' Value ';'
    1898     1270826 :   if (Lex.Lex() != tgtok::Id)
    1899           0 :     return TokError("expected field identifier after let");
    1900             : 
    1901      635413 :   SMLoc IdLoc = Lex.getLoc();
    1902      635413 :   StringInit *FieldName = StringInit::get(Lex.getCurStrVal());
    1903             :   Lex.Lex();  // eat the field name.
    1904             : 
    1905             :   SmallVector<unsigned, 16> BitList;
    1906      635413 :   if (ParseOptionalBitList(BitList))
    1907             :     return true;
    1908             :   std::reverse(BitList.begin(), BitList.end());
    1909             : 
    1910      635413 :   if (Lex.getCode() != tgtok::equal)
    1911           0 :     return TokError("expected '=' in let expression");
    1912             :   Lex.Lex();  // eat the '='.
    1913             : 
    1914             :   RecordVal *Field = CurRec->getValue(FieldName);
    1915      635413 :   if (!Field)
    1916           0 :     return TokError("Value '" + FieldName->getValue() + "' unknown!");
    1917             : 
    1918             :   RecTy *Type = Field->getType();
    1919             : 
    1920      635413 :   Init *Val = ParseValue(CurRec, Type);
    1921      635413 :   if (!Val) return true;
    1922             : 
    1923      635413 :   if (Lex.getCode() != tgtok::semi)
    1924           0 :     return TokError("expected ';' after let expression");
    1925             :   Lex.Lex();
    1926             : 
    1927      635413 :   return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
    1928             : }
    1929             : 
    1930             : /// ParseBody - Read the body of a class or def.  Return true on error, false on
    1931             : /// success.
    1932             : ///
    1933             : ///   Body     ::= ';'
    1934             : ///   Body     ::= '{' BodyList '}'
    1935             : ///   BodyList BodyItem*
    1936             : ///
    1937     2121297 : bool TGParser::ParseBody(Record *CurRec) {
    1938             :   // If this is a null definition, just eat the semi and return.
    1939     2121297 :   if (Lex.getCode() == tgtok::semi) {
    1940     1921055 :     Lex.Lex();
    1941     1921055 :     return false;
    1942             :   }
    1943             : 
    1944      200242 :   if (Lex.getCode() != tgtok::l_brace)
    1945           0 :     return TokError("Expected ';' or '{' to start body");
    1946             :   // Eat the '{'.
    1947      200242 :   Lex.Lex();
    1948             : 
    1949      986836 :   while (Lex.getCode() != tgtok::r_brace)
    1950      786594 :     if (ParseBodyItem(CurRec))
    1951             :       return true;
    1952             : 
    1953             :   // Eat the '}'.
    1954             :   Lex.Lex();
    1955      200242 :   return false;
    1956             : }
    1957             : 
    1958             : /// \brief Apply the current let bindings to \a CurRec.
    1959             : /// \returns true on error, false otherwise.
    1960     3190092 : bool TGParser::ApplyLetStack(Record *CurRec) {
    1961     4958104 :   for (SmallVectorImpl<LetRecord> &LetInfo : LetStack)
    1962     5606276 :     for (LetRecord &LR : LetInfo)
    1963     3838264 :       if (SetValue(CurRec, LR.Loc, LR.Name, LR.Bits, LR.Value))
    1964             :         return true;
    1965             :   return false;
    1966             : }
    1967             : 
    1968             : /// ParseObjectBody - Parse the body of a def or class.  This consists of an
    1969             : /// optional ClassList followed by a Body.  CurRec is the current def or class
    1970             : /// that is being parsed.
    1971             : ///
    1972             : ///   ObjectBody      ::= BaseClassList Body
    1973             : ///   BaseClassList   ::= /*empty*/
    1974             : ///   BaseClassList   ::= ':' BaseClassListNE
    1975             : ///   BaseClassListNE ::= SubClassRef (',' SubClassRef)*
    1976             : ///
    1977     2121297 : bool TGParser::ParseObjectBody(Record *CurRec) {
    1978             :   // If there is a baseclass list, read it.
    1979     2121297 :   if (Lex.getCode() == tgtok::colon) {
    1980     2098762 :     Lex.Lex();
    1981             : 
    1982             :     // Read all of the subclasses.
    1983     2098762 :     SubClassReference SubClass = ParseSubClassReference(CurRec, false);
    1984             :     while (true) {
    1985             :       // Check for error.
    1986     3473480 :       if (!SubClass.Rec) return true;
    1987             : 
    1988             :       // Add it.
    1989     2786121 :       if (AddSubClass(CurRec, SubClass))
    1990             :         return true;
    1991             : 
    1992     2786121 :       if (Lex.getCode() != tgtok::comma) break;
    1993             :       Lex.Lex(); // eat ','.
    1994     1374718 :       SubClass = ParseSubClassReference(CurRec, false);
    1995             :     }
    1996             :   }
    1997             : 
    1998     2121297 :   if (ApplyLetStack(CurRec))
    1999             :     return true;
    2000             : 
    2001     2121297 :   return ParseBody(CurRec);
    2002             : }
    2003             : 
    2004             : /// ParseDef - Parse and return a top level or multiclass def, return the record
    2005             : /// corresponding to it.  This returns null on error.
    2006             : ///
    2007             : ///   DefInst ::= DEF ObjectName ObjectBody
    2008             : ///
    2009     1962628 : bool TGParser::ParseDef(MultiClass *CurMultiClass) {
    2010     1962628 :   SMLoc DefLoc = Lex.getLoc();
    2011             :   assert(Lex.getCode() == tgtok::Def && "Unknown tok");
    2012             :   Lex.Lex();  // Eat the 'def' token.
    2013             : 
    2014             :   // Parse ObjectName and make a record for it.
    2015     3925256 :   std::unique_ptr<Record> CurRecOwner;
    2016     1962628 :   Init *Name = ParseObjectName(CurMultiClass);
    2017     1962628 :   if (Name)
    2018     1545071 :     CurRecOwner = make_unique<Record>(Name, DefLoc, Records);
    2019             :   else
    2020      417557 :     CurRecOwner = llvm::make_unique<Record>(GetNewAnonymousName(), DefLoc,
    2021             :                                             Records, /*IsAnonymous=*/true);
    2022             :   Record *CurRec = CurRecOwner.get(); // Keep a copy since we may release.
    2023             : 
    2024     3860770 :   if (!CurMultiClass && Loops.empty()) {
    2025             :     // Top-level def definition.
    2026             : 
    2027             :     // Ensure redefinition doesn't happen.
    2028     5687670 :     if (Records.getDef(CurRec->getNameInitAsString()))
    2029           0 :       return Error(DefLoc, "def '" + CurRec->getNameInitAsString()+
    2030             :                    "' already defined");
    2031     3791780 :     Records.addDef(std::move(CurRecOwner));
    2032             : 
    2033     1895890 :     if (ParseObjectBody(CurRec))
    2034             :       return true;
    2035       66738 :   } else if (CurMultiClass) {
    2036             :     // Parse the body before adding this prototype to the DefPrototypes vector.
    2037             :     // That way implicit definitions will be added to the DefPrototypes vector
    2038             :     // before this object, instantiated prior to defs derived from this object,
    2039             :     // and this available for indirect name resolution when defs derived from
    2040             :     // this object are instantiated.
    2041       64486 :     if (ParseObjectBody(CurRec))
    2042             :       return true;
    2043             : 
    2044             :     // Otherwise, a def inside a multiclass, add it to the multiclass.
    2045      292389 :     for (const auto &Proto : CurMultiClass->DefPrototypes)
    2046      227903 :       if (Proto->getNameInit() == CurRec->getNameInit())
    2047           0 :         return Error(DefLoc, "def '" + CurRec->getNameInitAsString() +
    2048             :                      "' already defined in this multiclass!");
    2049       64486 :     CurMultiClass->DefPrototypes.push_back(std::move(CurRecOwner));
    2050        2252 :   } else if (ParseObjectBody(CurRec)) {
    2051             :     return true;
    2052             :   }
    2053             : 
    2054     1962628 :   if (!CurMultiClass)  // Def's in multiclasses aren't really defs.
    2055             :     // See Record::setName().  This resolve step will see any new name
    2056             :     // for the def that might have been created when resolving
    2057             :     // inheritance, values and arguments above.
    2058             :     CurRec->resolveReferences();
    2059             : 
    2060             :   // If ObjectBody has template arguments, it's an error.
    2061             :   assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
    2062             : 
    2063     1962628 :   if (CurMultiClass) {
    2064             :     // Copy the template arguments for the multiclass into the def.
    2065      541696 :     for (Init *TArg : CurMultiClass->Rec.getTemplateArgs()) {
    2066             :       const RecordVal *RV = CurMultiClass->Rec.getValue(TArg);
    2067             :       assert(RV && "Template arg doesn't exist?");
    2068      238605 :       CurRec->addValue(*RV);
    2069             :     }
    2070             :   }
    2071             : 
    2072     1962628 :   if (ProcessForeachDefs(CurRec, DefLoc))
    2073           0 :     return Error(DefLoc, "Could not process loops for def" +
    2074           0 :                  CurRec->getNameInitAsString());
    2075             : 
    2076             :   return false;
    2077             : }
    2078             : 
    2079             : /// ParseForeach - Parse a for statement.  Return the record corresponding
    2080             : /// to it.  This returns true on error.
    2081             : ///
    2082             : ///   Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
    2083             : ///   Foreach ::= FOREACH Declaration IN Object
    2084             : ///
    2085        1298 : bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
    2086             :   assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
    2087        1298 :   Lex.Lex();  // Eat the 'for' token.
    2088             : 
    2089             :   // Make a temporary object to record items associated with the for
    2090             :   // loop.
    2091        1298 :   ListInit *ListValue = nullptr;
    2092        1298 :   VarInit *IterName = ParseForeachDeclaration(ListValue);
    2093        1298 :   if (!IterName)
    2094           0 :     return TokError("expected declaration in for");
    2095             : 
    2096        1298 :   if (Lex.getCode() != tgtok::In)
    2097           0 :     return TokError("Unknown tok");
    2098             :   Lex.Lex();  // Eat the in
    2099             : 
    2100             :   // Create a loop object and remember it.
    2101        2596 :   Loops.push_back(ForeachLoop(IterName, ListValue));
    2102             : 
    2103        1298 :   if (Lex.getCode() != tgtok::l_brace) {
    2104             :     // FOREACH Declaration IN Object
    2105         303 :     if (ParseObject(CurMultiClass))
    2106             :       return true;
    2107             :   } else {
    2108         995 :     SMLoc BraceLoc = Lex.getLoc();
    2109             :     // Otherwise, this is a group foreach.
    2110             :     Lex.Lex();  // eat the '{'.
    2111             : 
    2112             :     // Parse the object list.
    2113         995 :     if (ParseObjectList(CurMultiClass))
    2114           0 :       return true;
    2115             : 
    2116         995 :     if (Lex.getCode() != tgtok::r_brace) {
    2117           0 :       TokError("expected '}' at end of foreach command");
    2118           0 :       return Error(BraceLoc, "to match this '{'");
    2119             :     }
    2120             :     Lex.Lex();  // Eat the }
    2121             :   }
    2122             : 
    2123             :   // We've processed everything in this loop.
    2124             :   Loops.pop_back();
    2125             : 
    2126        1298 :   return false;
    2127             : }
    2128             : 
    2129             : /// ParseClass - Parse a tblgen class definition.
    2130             : ///
    2131             : ///   ClassInst ::= CLASS ID TemplateArgList? ObjectBody
    2132             : ///
    2133      158669 : bool TGParser::ParseClass() {
    2134             :   assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
    2135      158669 :   Lex.Lex();
    2136             : 
    2137      158669 :   if (Lex.getCode() != tgtok::Id)
    2138           0 :     return TokError("expected class name after 'class' keyword");
    2139             : 
    2140      317338 :   Record *CurRec = Records.getClass(Lex.getCurStrVal());
    2141      158669 :   if (CurRec) {
    2142             :     // If the body was previously defined, this is an error.
    2143         816 :     if (CurRec->getValues().size() > 1 ||  // Account for NAME.
    2144        1632 :         !CurRec->getSuperClasses().empty() ||
    2145             :         !CurRec->getTemplateArgs().empty())
    2146           0 :       return TokError("Class '" + CurRec->getNameInitAsString() +
    2147           0 :                       "' already defined");
    2148             :   } else {
    2149             :     // If this is the first reference to this class, create and add it.
    2150             :     auto NewRec =
    2151      473559 :         llvm::make_unique<Record>(Lex.getCurStrVal(), Lex.getLoc(), Records);
    2152             :     CurRec = NewRec.get();
    2153      315706 :     Records.addClass(std::move(NewRec));
    2154             :   }
    2155             :   Lex.Lex(); // eat the name.
    2156             : 
    2157             :   // If there are template args, parse them.
    2158      158669 :   if (Lex.getCode() == tgtok::less)
    2159      104922 :     if (ParseTemplateArgList(CurRec))
    2160             :       return true;
    2161             : 
    2162             :   // Finally, parse the object body.
    2163      158669 :   return ParseObjectBody(CurRec);
    2164             : }
    2165             : 
    2166             : /// ParseLetList - Parse a non-empty list of assignment expressions into a list
    2167             : /// of LetRecords.
    2168             : ///
    2169             : ///   LetList ::= LetItem (',' LetItem)*
    2170             : ///   LetItem ::= ID OptionalRangeList '=' Value
    2171             : ///
    2172       83012 : void TGParser::ParseLetList(SmallVectorImpl<LetRecord> &Result) {
    2173             :   while (true) {
    2174      113972 :     if (Lex.getCode() != tgtok::Id) {
    2175           0 :       TokError("expected identifier in let definition");
    2176           0 :       Result.clear();
    2177       83012 :       return;
    2178             :     }
    2179             : 
    2180      113972 :     StringInit *Name = StringInit::get(Lex.getCurStrVal());
    2181      113972 :     SMLoc NameLoc = Lex.getLoc();
    2182             :     Lex.Lex();  // Eat the identifier.
    2183             : 
    2184             :     // Check for an optional RangeList.
    2185             :     SmallVector<unsigned, 16> Bits;
    2186      113972 :     if (ParseOptionalRangeList(Bits)) {
    2187           0 :       Result.clear();
    2188           0 :       return;
    2189             :     }
    2190             :     std::reverse(Bits.begin(), Bits.end());
    2191             : 
    2192      113972 :     if (Lex.getCode() != tgtok::equal) {
    2193           0 :       TokError("expected '=' in let expression");
    2194           0 :       Result.clear();
    2195           0 :       return;
    2196             :     }
    2197             :     Lex.Lex();  // eat the '='.
    2198             : 
    2199      113972 :     Init *Val = ParseValue(nullptr);
    2200      113972 :     if (!Val) {
    2201           0 :       Result.clear();
    2202           0 :       return;
    2203             :     }
    2204             : 
    2205             :     // Now that we have everything, add the record.
    2206      113972 :     Result.emplace_back(Name, Bits, Val, NameLoc);
    2207             : 
    2208      113972 :     if (Lex.getCode() != tgtok::comma)
    2209             :       return;
    2210             :     Lex.Lex();  // eat the comma.
    2211             :   }
    2212             : }
    2213             : 
    2214             : /// ParseTopLevelLet - Parse a 'let' at top level.  This can be a couple of
    2215             : /// different related productions. This works inside multiclasses too.
    2216             : ///
    2217             : ///   Object ::= LET LetList IN '{' ObjectList '}'
    2218             : ///   Object ::= LET LetList IN Object
    2219             : ///
    2220       83012 : bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
    2221             :   assert(Lex.getCode() == tgtok::Let && "Unexpected token");
    2222       83012 :   Lex.Lex();
    2223             : 
    2224             :   // Add this entry to the let stack.
    2225       83012 :   SmallVector<LetRecord, 8> LetInfo;
    2226       83012 :   ParseLetList(LetInfo);
    2227       83012 :   if (LetInfo.empty()) return true;
    2228      166024 :   LetStack.push_back(std::move(LetInfo));
    2229             : 
    2230       83012 :   if (Lex.getCode() != tgtok::In)
    2231           0 :     return TokError("expected 'in' at end of top-level 'let'");
    2232             :   Lex.Lex();
    2233             : 
    2234             :   // If this is a scalar let, just handle it now
    2235       83012 :   if (Lex.getCode() != tgtok::l_brace) {
    2236             :     // LET LetList IN Object
    2237       20689 :     if (ParseObject(CurMultiClass))
    2238             :       return true;
    2239             :   } else {   // Object ::= LETCommand '{' ObjectList '}'
    2240       62323 :     SMLoc BraceLoc = Lex.getLoc();
    2241             :     // Otherwise, this is a group let.
    2242             :     Lex.Lex();  // eat the '{'.
    2243             : 
    2244             :     // Parse the object list.
    2245       62323 :     if (ParseObjectList(CurMultiClass))
    2246           0 :       return true;
    2247             : 
    2248       62323 :     if (Lex.getCode() != tgtok::r_brace) {
    2249           0 :       TokError("expected '}' at end of top level let command");
    2250           0 :       return Error(BraceLoc, "to match this '{'");
    2251             :     }
    2252             :     Lex.Lex();
    2253             :   }
    2254             : 
    2255             :   // Outside this let scope, this let block is not active.
    2256             :   LetStack.pop_back();
    2257       83012 :   return false;
    2258             : }
    2259             : 
    2260             : /// ParseMultiClass - Parse a multiclass definition.
    2261             : ///
    2262             : ///  MultiClassInst ::= MULTICLASS ID TemplateArgList?
    2263             : ///                     ':' BaseMultiClassList '{' MultiClassObject+ '}'
    2264             : ///  MultiClassObject ::= DefInst
    2265             : ///  MultiClassObject ::= MultiClassInst
    2266             : ///  MultiClassObject ::= DefMInst
    2267             : ///  MultiClassObject ::= LETCommand '{' ObjectList '}'
    2268             : ///  MultiClassObject ::= LETCommand Object
    2269             : ///
    2270       24173 : bool TGParser::ParseMultiClass() {
    2271             :   assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
    2272       24173 :   Lex.Lex();  // Eat the multiclass token.
    2273             : 
    2274       24173 :   if (Lex.getCode() != tgtok::Id)
    2275           0 :     return TokError("expected identifier after multiclass for name");
    2276             :   std::string Name = Lex.getCurStrVal();
    2277             : 
    2278             :   auto Result =
    2279       24173 :     MultiClasses.insert(std::make_pair(Name,
    2280       48346 :                     llvm::make_unique<MultiClass>(Name, Lex.getLoc(),Records)));
    2281             : 
    2282       24173 :   if (!Result.second)
    2283           0 :     return TokError("multiclass '" + Name + "' already defined");
    2284             : 
    2285       24173 :   CurMultiClass = Result.first->second.get();
    2286             :   Lex.Lex();  // Eat the identifier.
    2287             : 
    2288             :   // If there are template args, parse them.
    2289       24173 :   if (Lex.getCode() == tgtok::less)
    2290       22962 :     if (ParseTemplateArgList(nullptr))
    2291             :       return true;
    2292             : 
    2293             :   bool inherits = false;
    2294             : 
    2295             :   // If there are submulticlasses, parse them.
    2296       24173 :   if (Lex.getCode() == tgtok::colon) {
    2297             :     inherits = true;
    2298             : 
    2299             :     Lex.Lex();
    2300             : 
    2301             :     // Read all of the submulticlasses.
    2302             :     SubMultiClassReference SubMultiClass =
    2303        1767 :       ParseSubMultiClassReference(CurMultiClass);
    2304             :     while (true) {
    2305             :       // Check for error.
    2306        1877 :       if (!SubMultiClass.MC) return true;
    2307             : 
    2308             :       // Add it.
    2309        1822 :       if (AddSubMultiClass(CurMultiClass, SubMultiClass))
    2310             :         return true;
    2311             : 
    2312        1822 :       if (Lex.getCode() != tgtok::comma) break;
    2313             :       Lex.Lex(); // eat ','.
    2314         110 :       SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
    2315             :     }
    2316             :   }
    2317             : 
    2318       24173 :   if (Lex.getCode() != tgtok::l_brace) {
    2319         509 :     if (!inherits)
    2320           0 :       return TokError("expected '{' in multiclass definition");
    2321         509 :     if (Lex.getCode() != tgtok::semi)
    2322           0 :       return TokError("expected ';' in multiclass definition");
    2323             :     Lex.Lex();  // eat the ';'.
    2324             :   } else {
    2325       23664 :     if (Lex.Lex() == tgtok::r_brace)  // eat the '{'.
    2326           0 :       return TokError("multiclass must contain at least one def");
    2327             : 
    2328       92037 :     while (Lex.getCode() != tgtok::r_brace) {
    2329             :       switch (Lex.getCode()) {
    2330             :       default:
    2331           0 :         return TokError("expected 'let', 'def' or 'defm' in multiclass body");
    2332       68373 :       case tgtok::Let:
    2333             :       case tgtok::Def:
    2334             :       case tgtok::Defm:
    2335             :       case tgtok::Foreach:
    2336       68373 :         if (ParseObject(CurMultiClass))
    2337             :           return true;
    2338             :         break;
    2339             :       }
    2340             :     }
    2341             :     Lex.Lex();  // eat the '}'.
    2342             :   }
    2343             : 
    2344       24173 :   CurMultiClass = nullptr;
    2345       24173 :   return false;
    2346             : }
    2347             : 
    2348      798768 : Record *TGParser::InstantiateMulticlassDef(MultiClass &MC, Record *DefProto,
    2349             :                                            Init *&DefmPrefix,
    2350             :                                            SMRange DefmPrefixRange,
    2351             :                                            ArrayRef<Init *> TArgs,
    2352             :                                            ArrayRef<Init *> TemplateVals) {
    2353             :   // We need to preserve DefProto so it can be reused for later
    2354             :   // instantiations, so create a new Record to inherit from it.
    2355             : 
    2356             :   // Add in the defm name.  If the defm prefix is empty, give each
    2357             :   // instantiated def a unique name.  Otherwise, if "#NAME#" exists in the
    2358             :   // name, substitute the prefix for #NAME#.  Otherwise, use the defm name
    2359             :   // as a prefix.
    2360             : 
    2361             :   bool IsAnonymous = false;
    2362      798768 :   if (!DefmPrefix) {
    2363       27011 :     DefmPrefix = GetNewAnonymousName();
    2364             :     IsAnonymous = true;
    2365             :   }
    2366             : 
    2367      798768 :   Init *DefName = DefProto->getNameInit();
    2368             :   StringInit *DefNameString = dyn_cast<StringInit>(DefName);
    2369             : 
    2370             :   if (DefNameString) {
    2371             :     // We have a fully expanded string so there are no operators to
    2372             :     // resolve.  We should concatenate the given prefix and name.
    2373             :     DefName =
    2374      682726 :       BinOpInit::get(BinOpInit::STRCONCAT,
    2375      682726 :                      UnOpInit::get(UnOpInit::CAST, DefmPrefix,
    2376      682726 :                                    StringRecTy::get())->Fold(DefProto, &MC),
    2377      682726 :                      DefName, StringRecTy::get())->Fold(DefProto, &MC);
    2378             :   }
    2379             : 
    2380             :   // Make a trail of SMLocs from the multiclass instantiations.
    2381             :   SmallVector<SMLoc, 4> Locs(1, DefmPrefixRange.Start);
    2382      798768 :   Locs.append(DefProto->getLoc().begin(), DefProto->getLoc().end());
    2383     1597536 :   auto CurRec = make_unique<Record>(DefName, Locs, Records, IsAnonymous);
    2384             : 
    2385             :   SubClassReference Ref;
    2386      798768 :   Ref.RefRange = DefmPrefixRange;
    2387      798768 :   Ref.Rec = DefProto;
    2388      798768 :   AddSubClass(CurRec.get(), Ref);
    2389             : 
    2390             :   // Set the value for NAME. We don't resolve references to it 'til later,
    2391             :   // though, so that uses in nested multiclass names don't get
    2392             :   // confused.
    2393     2396304 :   if (SetValue(CurRec.get(), Ref.RefRange.Start, StringInit::get("NAME"), None,
    2394             :                DefmPrefix, /*AllowSelfAssignment*/true)) {
    2395           0 :     Error(DefmPrefixRange.Start, "Could not resolve " +
    2396           0 :           CurRec->getNameInitAsString() + ":NAME to '" +
    2397           0 :           DefmPrefix->getAsUnquotedString() + "'");
    2398           0 :     return nullptr;
    2399             :   }
    2400             : 
    2401             :   // If the DefNameString didn't resolve, we probably have a reference to
    2402             :   // NAME and need to replace it. We need to do at least this much greedily,
    2403             :   // otherwise nested multiclasses will end up with incorrect NAME expansions.
    2404      798768 :   if (!DefNameString) {
    2405      116042 :     RecordVal *DefNameRV = CurRec->getValue("NAME");
    2406      116042 :     CurRec->resolveReferencesTo(DefNameRV);
    2407             :   }
    2408             : 
    2409      798768 :   if (!CurMultiClass) {
    2410             :     // Now that we're at the top level, resolve all NAME references
    2411             :     // in the resultant defs that weren't in the def names themselves.
    2412      696187 :     RecordVal *DefNameRV = CurRec->getValue("NAME");
    2413      696187 :     CurRec->resolveReferencesTo(DefNameRV);
    2414             : 
    2415             :     // Check if the name is a complex pattern.
    2416             :     // If so, resolve it.
    2417      696187 :     DefName = CurRec->getNameInit();
    2418             :     DefNameString = dyn_cast<StringInit>(DefName);
    2419             : 
    2420             :     // OK the pattern is more complex than simply using NAME.
    2421             :     // Let's use the heavy weaponery.
    2422             :     if (!DefNameString) {
    2423        5000 :       ResolveMulticlassDefArgs(MC, CurRec.get(), DefmPrefixRange.Start,
    2424             :                                Lex.getLoc(), TArgs, TemplateVals,
    2425             :                                false/*Delete args*/);
    2426        2500 :       DefName = CurRec->getNameInit();
    2427             :       DefNameString = dyn_cast<StringInit>(DefName);
    2428             : 
    2429             :       if (!DefNameString)
    2430           0 :         DefName = DefName->convertInitializerTo(StringRecTy::get());
    2431             : 
    2432             :       // We ran out of options here...
    2433             :       DefNameString = dyn_cast<StringInit>(DefName);
    2434             :       if (!DefNameString) {
    2435           0 :         PrintFatalError(CurRec->getLoc()[CurRec->getLoc().size() - 1],
    2436           0 :                         DefName->getAsUnquotedString() + " is not a string.");
    2437             :         return nullptr;
    2438             :       }
    2439             : 
    2440        2500 :       CurRec->setName(DefName);
    2441             :     }
    2442             : 
    2443             :     // Now that NAME references are resolved and we're at the top level of
    2444             :     // any multiclass expansions, add the record to the RecordKeeper. If we are
    2445             :     // currently in a multiclass, it means this defm appears inside a
    2446             :     // multiclass and its name won't be fully resolvable until we see
    2447             :     // the top-level defm. Therefore, we don't add this to the
    2448             :     // RecordKeeper at this point. If we did we could get duplicate
    2449             :     // defs as more than one probably refers to NAME or some other
    2450             :     // common internal placeholder.
    2451             : 
    2452             :     // Ensure redefinition doesn't happen.
    2453     2088561 :     if (Records.getDef(CurRec->getNameInitAsString())) {
    2454           0 :       Error(DefmPrefixRange.Start, "def '" + CurRec->getNameInitAsString() +
    2455           0 :             "' already defined, instantiating defm with subdef '" + 
    2456           0 :             DefProto->getNameInitAsString() + "'");
    2457           0 :       return nullptr;
    2458             :     }
    2459             : 
    2460             :     Record *CurRecSave = CurRec.get(); // Keep a copy before we release.
    2461     1392374 :     Records.addDef(std::move(CurRec));
    2462      696187 :     return CurRecSave;
    2463             :   }
    2464             : 
    2465             :   // FIXME This is bad but the ownership transfer to caller is pretty messy.
    2466             :   // The unique_ptr in this function at least protects the exits above.
    2467      102581 :   return CurRec.release();
    2468             : }
    2469             : 
    2470      801268 : bool TGParser::ResolveMulticlassDefArgs(MultiClass &MC, Record *CurRec,
    2471             :                                         SMLoc DefmPrefixLoc, SMLoc SubClassLoc,
    2472             :                                         ArrayRef<Init *> TArgs,
    2473             :                                         ArrayRef<Init *> TemplateVals,
    2474             :                                         bool DeleteArgs) {
    2475             :   // Loop over all of the template arguments, setting them to the specified
    2476             :   // value or leaving them as the default if necessary.
    2477     3881788 :   for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
    2478             :     // Check if a value is specified for this temp-arg.
    2479     3080520 :     if (i < TemplateVals.size()) {
    2480             :       // Set it now.
    2481     8816577 :       if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], None, TemplateVals[i]))
    2482             :         return true;
    2483             : 
    2484             :       // Resolve it next.
    2485     5877718 :       CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
    2486             : 
    2487     2938859 :       if (DeleteArgs)
    2488             :         // Now remove it.
    2489     2915143 :         CurRec->removeValue(TArgs[i]);
    2490             : 
    2491      283322 :     } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
    2492           0 :       return Error(SubClassLoc, "value not specified for template argument #" +
    2493           0 :                    Twine(i) + " (" + TArgs[i]->getAsUnquotedString() +
    2494           0 :                    ") of multiclassclass '" + MC.Rec.getNameInitAsString() +
    2495           0 :                    "'");
    2496             :     }
    2497             :   }
    2498             :   return false;
    2499             : }
    2500             : 
    2501      798768 : bool TGParser::ResolveMulticlassDef(MultiClass &MC,
    2502             :                                     Record *CurRec,
    2503             :                                     Record *DefProto,
    2504             :                                     SMLoc DefmPrefixLoc) {
    2505             :   // If the mdef is inside a 'let' expression, add to each def.
    2506      798768 :   if (ApplyLetStack(CurRec))
    2507           0 :     return Error(DefmPrefixLoc, "when instantiating this defm");
    2508             : 
    2509             :   // Don't create a top level definition for defm inside multiclasses,
    2510             :   // instead, only update the prototypes and bind the template args
    2511             :   // with the new created definition.
    2512      798768 :   if (!CurMultiClass)
    2513             :     return false;
    2514     2148008 :   for (const auto &Proto : CurMultiClass->DefPrototypes)
    2515     2045427 :     if (Proto->getNameInit() == CurRec->getNameInit())
    2516           0 :       return Error(DefmPrefixLoc, "defm '" + CurRec->getNameInitAsString() +
    2517             :                    "' already defined in this multiclass!");
    2518      205162 :   CurMultiClass->DefPrototypes.push_back(std::unique_ptr<Record>(CurRec));
    2519             : 
    2520             :   // Copy the template arguments for the multiclass into the new def.
    2521     1057224 :   for (Init * TA : CurMultiClass->Rec.getTemplateArgs()) {
    2522      426031 :     const RecordVal *RV = CurMultiClass->Rec.getValue(TA);
    2523             :     assert(RV && "Template arg doesn't exist?");
    2524      426031 :     CurRec->addValue(*RV);
    2525             :   }
    2526             : 
    2527             :   return false;
    2528             : }
    2529             : 
    2530             : /// ParseDefm - Parse the instantiation of a multiclass.
    2531             : ///
    2532             : ///   DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
    2533             : ///
    2534      121280 : bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
    2535             :   assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
    2536      121280 :   SMLoc DefmLoc = Lex.getLoc();
    2537      121280 :   Init *DefmPrefix = nullptr;
    2538             : 
    2539      121280 :   if (Lex.Lex() == tgtok::Id) {  // eat the defm.
    2540       94269 :     DefmPrefix = ParseObjectName(CurMultiClass);
    2541             :   }
    2542             : 
    2543      121280 :   SMLoc DefmPrefixEndLoc = Lex.getLoc();
    2544      121280 :   if (Lex.getCode() != tgtok::colon)
    2545           0 :     return TokError("expected ':' after defm identifier");
    2546             : 
    2547             :   // Keep track of the new generated record definitions.
    2548             :   std::vector<Record*> NewRecDefs;
    2549             : 
    2550             :   // This record also inherits from a regular class (non-multiclass)?
    2551             :   bool InheritFromClass = false;
    2552             : 
    2553             :   // eat the colon.
    2554             :   Lex.Lex();
    2555             : 
    2556      121280 :   SMLoc SubClassLoc = Lex.getLoc();
    2557      121280 :   SubClassReference Ref = ParseSubClassReference(nullptr, true);
    2558             : 
    2559             :   while (true) {
    2560      123054 :     if (!Ref.Rec) return true;
    2561             : 
    2562             :     // To instantiate a multiclass, we need to first get the multiclass, then
    2563             :     // instantiate each def contained in the multiclass with the SubClassRef
    2564             :     // template parameters.
    2565      369162 :     MultiClass *MC = MultiClasses[Ref.Rec->getName()].get();
    2566             :     assert(MC && "Didn't lookup multiclass correctly?");
    2567             :     ArrayRef<Init*> TemplateVals = Ref.TemplateArgs;
    2568             : 
    2569             :     // Verify that the correct number of template arguments were specified.
    2570      123054 :     ArrayRef<Init *> TArgs = MC->Rec.getTemplateArgs();
    2571      123054 :     if (TArgs.size() < TemplateVals.size())
    2572           0 :       return Error(SubClassLoc,
    2573             :                    "more template args specified than multiclass expects");
    2574             : 
    2575             :     // Loop over all the def's in the multiclass, instantiating each one.
    2576      921822 :     for (const std::unique_ptr<Record> &DefProto : MC->DefPrototypes) {
    2577             :       // The record name construction goes as follow:
    2578             :       //  - If the def name is a string, prepend the prefix.
    2579             :       //  - If the def name is a more complex pattern, use that pattern.
    2580             :       // As a result, the record is instantiated before resolving
    2581             :       // arguments, as it would make its name a string.
    2582     1597536 :       Record *CurRec = InstantiateMulticlassDef(*MC, DefProto.get(), DefmPrefix,
    2583             :                                                 SMRange(DefmLoc,
    2584             :                                                         DefmPrefixEndLoc),
    2585      798768 :                                                 TArgs, TemplateVals);
    2586      798768 :       if (!CurRec)
    2587           0 :         return true;
    2588             : 
    2589             :       // Now that the record is instantiated, we can resolve arguments.
    2590      798768 :       if (ResolveMulticlassDefArgs(*MC, CurRec, DefmLoc, SubClassLoc,
    2591             :                                    TArgs, TemplateVals, true/*Delete args*/))
    2592           0 :         return Error(SubClassLoc, "could not instantiate def");
    2593             : 
    2594      798768 :       if (ResolveMulticlassDef(*MC, CurRec, DefProto.get(), DefmLoc))
    2595           0 :         return Error(SubClassLoc, "could not instantiate def");
    2596             : 
    2597             :       // Defs that can be used by other definitions should be fully resolved
    2598             :       // before any use.
    2599      798768 :       if (DefProto->isResolveFirst() && !CurMultiClass) {
    2600       10082 :         CurRec->resolveReferences();
    2601       10082 :         CurRec->setResolveFirst(false);
    2602             :       }
    2603      798768 :       NewRecDefs.push_back(CurRec);
    2604             :     }
    2605             : 
    2606             : 
    2607      123054 :     if (Lex.getCode() != tgtok::comma) break;
    2608             :     Lex.Lex(); // eat ','.
    2609             : 
    2610       19988 :     if (Lex.getCode() != tgtok::Id)
    2611           0 :       return TokError("expected identifier");
    2612             : 
    2613       19988 :     SubClassLoc = Lex.getLoc();
    2614             : 
    2615             :     // A defm can inherit from regular classes (non-multiclass) as
    2616             :     // long as they come in the end of the inheritance list.
    2617       39976 :     InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr);
    2618             : 
    2619       19988 :     if (InheritFromClass)
    2620             :       break;
    2621             : 
    2622        3548 :     Ref = ParseSubClassReference(nullptr, true);
    2623        1774 :   }
    2624             : 
    2625      121280 :   if (InheritFromClass) {
    2626             :     // Process all the classes to inherit as if they were part of a
    2627             :     // regular 'def' and inherit all record values.
    2628       18214 :     SubClassReference SubClass = ParseSubClassReference(nullptr, false);
    2629             :     while (true) {
    2630             :       // Check for error.
    2631       36104 :       if (!SubClass.Rec) return true;
    2632             : 
    2633             :       // Get the expanded definition prototypes and teach them about
    2634             :       // the record values the current class to inherit has
    2635      306131 :       for (Record *CurRec : NewRecDefs) {
    2636             :         // Add it.
    2637      270027 :         if (AddSubClass(CurRec, SubClass))
    2638             :           return true;
    2639             : 
    2640      270027 :         if (ApplyLetStack(CurRec))
    2641             :           return true;
    2642             :       }
    2643             : 
    2644       36104 :       if (Lex.getCode() != tgtok::comma) break;
    2645             :       Lex.Lex(); // eat ','.
    2646       35780 :       SubClass = ParseSubClassReference(nullptr, false);
    2647       17890 :     }
    2648             :   }
    2649             : 
    2650      121280 :   if (!CurMultiClass)
    2651      801785 :     for (Record *CurRec : NewRecDefs)
    2652             :       // See Record::setName().  This resolve step will see any new
    2653             :       // name for the def that might have been created when resolving
    2654             :       // inheritance, values and arguments above.
    2655             :       CurRec->resolveReferences();
    2656             : 
    2657      121280 :   if (Lex.getCode() != tgtok::semi)
    2658           0 :     return TokError("expected ';' at end of defm");
    2659             :   Lex.Lex();
    2660             : 
    2661      121280 :   return false;
    2662             : }
    2663             : 
    2664             : /// ParseObject
    2665             : ///   Object ::= ClassInst
    2666             : ///   Object ::= DefInst
    2667             : ///   Object ::= MultiClassInst
    2668             : ///   Object ::= DefMInst
    2669             : ///   Object ::= LETCommand '{' ObjectList '}'
    2670             : ///   Object ::= LETCommand Object
    2671     2351060 : bool TGParser::ParseObject(MultiClass *MC) {
    2672     2351060 :   switch (Lex.getCode()) {
    2673             :   default:
    2674           0 :     return TokError("Expected class, def, defm, multiclass or let definition");
    2675       83012 :   case tgtok::Let:   return ParseTopLevelLet(MC);
    2676     1962628 :   case tgtok::Def:   return ParseDef(MC);
    2677        1298 :   case tgtok::Foreach:   return ParseForeach(MC);
    2678      121280 :   case tgtok::Defm:  return ParseDefm(MC);
    2679      158669 :   case tgtok::Class: return ParseClass();
    2680       24173 :   case tgtok::MultiClass: return ParseMultiClass();
    2681             :   }
    2682             : }
    2683             : 
    2684             : /// ParseObjectList
    2685             : ///   ObjectList :== Object*
    2686       63607 : bool TGParser::ParseObjectList(MultiClass *MC) {
    2687     2325302 :   while (isObjectStart(Lex.getCode())) {
    2688     2261695 :     if (ParseObject(MC))
    2689             :       return true;
    2690             :   }
    2691             :   return false;
    2692             : }
    2693             : 
    2694         289 : bool TGParser::ParseFile() {
    2695         289 :   Lex.Lex(); // Prime the lexer.
    2696         289 :   if (ParseObjectList()) return true;
    2697             : 
    2698             :   // If we have unread input at the end of the file, report it.
    2699         289 :   if (Lex.getCode() == tgtok::Eof)
    2700             :     return false;
    2701             : 
    2702           1 :   return TokError("Unexpected input at top level");
    2703             : }

Generated by: LCOV version 1.13